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 { OfficeStatus } from '../../core/office-status'; import { ToasterService } from '../../core/toaster.service'; import { ConfirmDialogComponent } from '../../shared/confirm-dialog/confirm-dialog.component'; import { OfficeStatusService } from '../office-status.service'; @Component({ selector: 'app-office-status-detail', templateUrl: './office-status-detail.component.html', styleUrls: ['./office-status-detail.component.css'], }) export class OfficeStatusDetailComponent implements OnInit, AfterViewInit { @ViewChild('nameElement', { static: true }) nameElement?: ElementRef; form: FormGroup; item: OfficeStatus = new OfficeStatus(); constructor( private route: ActivatedRoute, private router: Router, private dialog: MatDialog, private fb: FormBuilder, private toaster: ToasterService, private ser: OfficeStatusService, ) { // Create form this.form = this.fb.group({ name: '', }); } ngOnInit() { this.route.data.subscribe((value) => { const data = value as { item: OfficeStatus }; this.showItem(data.item); }); } showItem(item: OfficeStatus) { this.item = item; this.form.setValue({ name: this.item.name || '', }); } ngAfterViewInit() { setTimeout(() => { if (this.nameElement !== undefined) { this.nameElement.nativeElement.focus(); } }, 0); } save() { this.ser.saveOrUpdate(this.getItem()).subscribe( () => { this.toaster.show('Success', ''); this.router.navigateByUrl('/office-statuses'); }, (error) => { this.toaster.show('Error', error); }, ); } delete() { this.ser.delete(this.item.id as string).subscribe( () => { this.toaster.show('Success', ''); this.router.navigateByUrl('/office-statuses'); }, (error) => { this.toaster.show('Error', error); }, ); } confirmDelete(): void { const dialogRef = this.dialog.open(ConfirmDialogComponent, { width: '250px', data: { title: 'Delete Office Status?', content: 'Are you sure? This cannot be undone.' }, }); dialogRef.afterClosed().subscribe((result: boolean) => { if (result) { this.delete(); } }); } getItem(): OfficeStatus { const formModel = this.form.value; this.item.name = formModel.name; return this.item; } }