import { Component, inject, afterNextRender, linkedSignal, input, computed } from '@angular/core'; import { form as createForm, FormField, FormRoot } from '@angular/forms/signals'; import { MatButtonModule } from '@angular/material/button'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatSnackBar } from '@angular/material/snack-bar'; import { Router } from '@angular/router'; import { ProductGroup } from '../../core/product-group'; import { ErrorStateComponent } from '../../shared/error-state/error-state.component'; import { SkeletonLoaderComponent } from '../../shared/skeleton-loader/skeleton-loader.component'; import { ProductGroupService } from '../product-group.service'; export interface ProductGroupDetailFormData { name: string; nutritional: boolean; iceCream: boolean; } @Component({ selector: 'app-product-group-detail', templateUrl: './product-group-detail.component.html', styleUrls: ['./product-group-detail.component.css'], imports: [ FormField, FormRoot, MatFormFieldModule, MatInputModule, MatCheckboxModule, MatButtonModule, SkeletonLoaderComponent, ErrorStateComponent, ], }) export class ProductGroupDetailComponent { private router = inject(Router); private snackBar = inject(MatSnackBar); private ser = inject(ProductGroupService); id = input(null, { transform: (v: string | null | undefined) => v ?? null }); itemResource = this.ser.get(this.id); item = computed(() => this.itemResource.value() ?? new ProductGroup()); model = linkedSignal({ source: this.item, computation: (itemVal): ProductGroupDetailFormData => ({ name: itemVal.name ?? '', nutritional: itemVal.nutritional ?? false, iceCream: itemVal.iceCream ?? false, }), }); form = createForm(this.model); constructor() { afterNextRender(() => { this.form().focusBoundControl(); }); } save() { this.ser.saveOrUpdate(this.getItem()).subscribe({ next: () => { this.snackBar.open('', 'Success'); this.router.navigateByUrl('/product-groups'); }, error: (error) => { this.snackBar.open(error as string, 'Danger'); }, }); } getItem(): ProductGroup { const formModel = this.model(); const item = this.item(); item.name = formModel.name ?? ''; item.nutritional = formModel.nutritional ?? false; item.iceCream = formModel.iceCream ?? false; return item; } }