import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import { FormBuilder, 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; item: CostCentre; constructor( private route: ActivatedRoute, private router: Router, private fb: FormBuilder, private toaster: ToasterService, private ser: CostCentreService, ) { this.form = this.fb.group({ name: '', }); } 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(() => { 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; } }