import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { MatDialog } from "@angular/material"; import { ProductGroupService } from '../product-group.service'; import { ProductGroup } from '../../core/product-group'; import { ToasterService } from '../../core/toaster.service'; import { ConfirmDialogComponent } from "../../shared/confirm-dialog/confirm-dialog.component"; @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; item: ProductGroup; constructor( private route: ActivatedRoute, private router: Router, private dialog: MatDialog, private fb: FormBuilder, private toaster: ToasterService, private ser: ProductGroupService ) { this.createForm(); } createForm() { this.form = this.fb.group({ name: '', discountLimit: '', isModifierCompulsory: '', groupType: '', isActive: '' }); } ngOnInit() { this.route.data .subscribe((data: { item: ProductGroup }) => { this.showItem(data.item); }); } showItem(item: ProductGroup) { this.item = item; this.form.setValue({ name: this.item.name, discountLimit: this.item.discountLimit, isModifierCompulsory: this.item.isModifierCompulsory, groupType: this.item.groupType, isActive: this.item.isActive }); } ngAfterViewInit() { setTimeout(() => { this.nameElement.nativeElement.focus(); }, 0); } save() { this.ser.saveOrUpdate(this.getItem()) .subscribe( (result) => { this.toaster.show('Success', ''); this.router.navigateByUrl('/product-groups'); }, (error) => { this.toaster.show('Danger', error.error); } ); } delete() { this.ser.delete(this.item.id) .subscribe( (result) => { this.toaster.show('Success', ''); this.router.navigateByUrl('/product-groups'); }, (error) => { this.toaster.show('Danger', error.error); } ); } confirmDelete(): void { const dialogRef = this.dialog.open(ConfirmDialogComponent, { width: '250px', data: {title: 'Delete Product Group?', content: 'Are you sure? This cannot be undone.'} }); dialogRef.afterClosed().subscribe((result: boolean) => { if (result) { this.delete(); } }); } getItem(): ProductGroup { const formModel = this.form.value; this.item.name = formModel.name; this.item.discountLimit = +formModel.discountLimit; this.item.isModifierCompulsory = formModel.isModifierCompulsory; this.item.groupType = formModel.groupType; this.item.isActive = formModel.isActive; return this.item; } }