106 lines
2.7 KiB
TypeScript
106 lines
2.7 KiB
TypeScript
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
|
|
import { FormBuilder, FormGroup } from '@angular/forms';
|
|
import { MatDialog } from '@angular/material/dialog';
|
|
import { ActivatedRoute, Router } from '@angular/router';
|
|
|
|
import { Device } from '../../core/device';
|
|
import { Section } from '../../core/section';
|
|
import { ToasterService } from '../../core/toaster.service';
|
|
import { ConfirmDialogComponent } from '../../shared/confirm-dialog/confirm-dialog.component';
|
|
import { DeviceService } from '../device.service';
|
|
|
|
@Component({
|
|
selector: 'app-device-detail',
|
|
templateUrl: './device-detail.component.html',
|
|
styleUrls: ['./device-detail.component.css'],
|
|
})
|
|
export class DeviceDetailComponent implements OnInit, AfterViewInit {
|
|
@ViewChild('nameElement', { static: true }) nameElement: ElementRef;
|
|
form: FormGroup;
|
|
sections: Section[];
|
|
item: Device;
|
|
|
|
constructor(
|
|
private route: ActivatedRoute,
|
|
private router: Router,
|
|
private dialog: MatDialog,
|
|
private fb: FormBuilder,
|
|
private toaster: ToasterService,
|
|
private ser: DeviceService,
|
|
) {
|
|
this.createForm();
|
|
}
|
|
|
|
createForm() {
|
|
this.form = this.fb.group({
|
|
name: '',
|
|
section: '',
|
|
});
|
|
}
|
|
|
|
ngOnInit() {
|
|
this.route.data.subscribe((data: { item: Device; sections: Section[] }) => {
|
|
this.showItem(data.item);
|
|
this.sections = data.sections;
|
|
});
|
|
}
|
|
|
|
showItem(item: Device) {
|
|
this.item = item;
|
|
this.form.setValue({
|
|
name: this.item.name || '',
|
|
section: this.item.section.id ? this.item.section.id : '',
|
|
});
|
|
}
|
|
|
|
ngAfterViewInit() {
|
|
setTimeout(() => {
|
|
this.nameElement.nativeElement.focus();
|
|
}, 0);
|
|
}
|
|
|
|
save() {
|
|
this.ser.saveOrUpdate(this.getItem()).subscribe(
|
|
() => {
|
|
this.toaster.show('Success', '');
|
|
this.router.navigateByUrl('/devices');
|
|
},
|
|
(error) => {
|
|
this.toaster.show('Danger', error.error);
|
|
},
|
|
);
|
|
}
|
|
|
|
delete() {
|
|
this.ser.delete(this.item.id).subscribe(
|
|
() => {
|
|
this.toaster.show('Success', '');
|
|
this.router.navigateByUrl('/devices');
|
|
},
|
|
(error) => {
|
|
this.toaster.show('Danger', error.error);
|
|
},
|
|
);
|
|
}
|
|
|
|
confirmDelete(): void {
|
|
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
|
|
width: '250px',
|
|
data: { title: 'Delete Device?', content: 'Are you sure? This cannot be undone.' },
|
|
});
|
|
|
|
dialogRef.afterClosed().subscribe((result: boolean) => {
|
|
if (result) {
|
|
this.delete();
|
|
}
|
|
});
|
|
}
|
|
|
|
getItem(): Device {
|
|
const formModel = this.form.value;
|
|
this.item.name = formModel.name;
|
|
this.item.section.id = formModel.section;
|
|
return this.item;
|
|
}
|
|
}
|