I have made use of a generic approach where on adding a food item, a modal with a form will open to let the user add his details. However, for the check on backend for duplicate items, i can only retrieve that after the api call has finished.
The thing is I dont want the modal to be close if there is error as user has to fill all his details again.
Here is my code. I have used third party libraries for modal and toast.
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)
});
}
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>
custom – table.component.ts :
openModal(rowData: any = null) {
const config: Partial<DynamicFormComponent> = {
form: this.form,
data: rowData
};
const options: NgbModalOptions = { size: 'sm', centered: true };
this.ModalService.show((DynamicFormComponent), config, options).subscribe((result: any) => {
if (result.Success == true && result.Data) {
if (rowData) {
const updatedRowData = { ...rowData, ...result.Data };
// If rowData is provided, it's an edit operation
this.onEdit.emit(updatedRowData);
} else { //add
this.onAdd.emit(result.Data);
}
}
});
}
How to solve this?
2
Answers
You can cancel the
hide.bs.modal
event, based on your conditionNot use "close". Add to your component in modal a Subject, and subscribe when open. Is the component that open the popup who close the popup
Then, when open
A stackblitz (only close if you write "Angular" in the "name")
NOTE: you can improve indicating the reason it’s not valid the "form" or you can use a custom async validator.