// angular import { Component, DestroyRef, inject } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { HttpClient } from '@angular/common/http'; import { Inject } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; // libs import { MAT_DIALOG_DATA } from '@angular/material/dialog'; import { MatDialogRef } from '@angular/material/dialog'; // app import { ApiRoutes } from '../../../api-routes'; import { ItemCategoryModel } from '../../../model/item.category.model'; import { ItemModel } from '../../../model/item.model'; import { ItemService } from '../../../services/item.service'; @Component({ templateUrl: './edit.item.component.html', styleUrls: ['./edit.item.component.scss'], }) export class SettingsItemEditComponent { public editForm!: FormGroup; public errorMessage?: string; public categories?: ItemCategoryModel[]; private readonly destroyRef = inject(DestroyRef); constructor( private fb: FormBuilder, private httpClient: HttpClient, private dialogRef: MatDialogRef, private itemService: ItemService, @Inject(MAT_DIALOG_DATA) public item: ItemModel ) { } ngOnInit(): void { this.editForm = this.fb.group({ id: [ this.item.id, ], name: [ this.item.name, [Validators.required], ], category: [ this.item.categoryId, [Validators.required], ], }); this.itemService .getCategories() .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe(x => this.categories = x); } closeDialog(): void { this.dialogRef.close(); } onSubmitClick() { console.log(this.item); console.log(this.editForm.value); if (this.editForm.valid) { this.errorMessage = undefined; this.httpClient .put(ApiRoutes.SettingsItem.replace(':id', this.item.id!), this.editForm.value) .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe(response => { this.dialogRef.close({ motion: response, refresh: true }); }, error => { this.errorMessage = error.detail; }); } } }