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