My approach involves using a generic method where, upon adding a food item, a modal window with a form opens for the user to input their details. However, since backend validation for duplicate items can only be retrieved after the API call completes.
I want the modal to remain open in case of errors, as I don't want users to re-enter all their details again.
Below is my code. It includes third-party libraries for handling modals and toast messages.
In the file food.component.ts:
addFood(data: any){
this.api.request('foodItem', 'POST', data).subscribe({
next: (response: any) => {
if (response.message == 'Added Successfully.') {
this._toastService.showSuccess('Food added.');
} else {
this._toastService.showError(response.message);
}
},
complete: () => this.getFood(),
error: (error: any) => this._toastService.showError(error.message)
});
}
In the file food-component.html:
<app-custom-table [tableData]="tableData" [form]="formData" [columnArray]="columnArray" (onAdd)="addFood($event)" (onEdit)="editFood($event)"></app-custom-
table>
In custom-table.component.html:
<button type = "button" class="btn btn-link"(click) = "openModal()"[disabled] = "isRowSelected"><span>Add</span></button>
<button type="button" class="btn btn-link"(click) = "openModal(selectedRow)"[disabled] = "isRowNotSelected"></i><span>Edit</span></button>
In custom-table.component.ts:
openModal(rowData: any = null) {
const config: Partial<DynamicFormComponent> = {
form: this.form,
data: rowData
};
// more code would go here
In dynamic-form.html:
@Output() submitSub: Subject<any> = new Subject<any>();
constructor(
private activeModal: NgbActiveModal
){
}
onSubmit(){
if(this.dynamicFormGroup.valid){
this.submitSubject.next(this.dynamicFormGroup.value)
// not sure about the following line
this.activeModal.close(this.dynamicFodmGroup.value)
}
}
To resolve this issue, refer to the latest update in the code snippet above that attempts to deal with the problem related to reading properties of undefined during runtime.