import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { CostCentre } from '../../core/cost-centre'; import { ToasterService } from '../../core/toaster.service'; import { CostCentreService } from '../cost-centre.service'; @Component({ selector: 'app-cost-centre-detail', templateUrl: './cost-centre-detail.component.html', styleUrls: ['./cost-centre-detail.component.css'], }) export class CostCentreDetailComponent implements OnInit, AfterViewInit { @ViewChild('nameElement', { static: true }) nameElement?: ElementRef; form: FormGroup<{ name: FormControl; }>; item: CostCentre = new CostCentre(); constructor( private route: ActivatedRoute, private router: Router, private toaster: ToasterService, private ser: CostCentreService, ) { this.form = new FormGroup({ name: new FormControl(null), }); } ngOnInit() { this.route.data.subscribe((value) => { const data = value as { item: CostCentre }; this.showItem(data.item); }); } showItem(item: CostCentre) { this.item = item; this.form.setValue({ name: this.item.name, }); } ngAfterViewInit() { setTimeout(() => { if (this.nameElement) { this.nameElement.nativeElement.focus(); } }, 0); } save() { this.ser.saveOrUpdate(this.getItem()).subscribe( () => { this.toaster.show('Success', ''); this.router.navigateByUrl('/cost-centres'); }, (error) => { this.toaster.show('Danger', error); }, ); } getItem(): CostCentre { const formModel = this.form.value; this.item.name = formModel.name!; return this.item; } }