Hi,
I have an edit modal popup form (reactive). while loading the modal popup form controls are not being set with the values i get from api.
Console window gets the data but patchValue block is getting skipped without assigning the actual data.
// Load data
this.editdata = item; //getting projectId data correctly here in this.editdata
this.editForm.patchValue( /// not working. this line getting skipped and going out of this block
{
projectId:this.editdata[0].projectId,
});
Form group initialization code:
editForm = this.builder.group({
projectId: this.builder.control(''),
projectType: this.builder.control(''),
planNumber: this.builder.control(''),
planName: this.builder.control(''),
Naimish MakwanaPosted Jan 19, 2024, 6:20 AM
It seems like you’re having trouble with Angular’s
patchValuemethod. This method is used to update specific parts of a form control.Here are a few things you could check:
Asynchronous Data: If the data you’re trying to patch is being fetched asynchronously (like from an API), you need to ensure that the data is available before you try to patch the form. You might be trying to patch the form before the data has been returned from the API.
Form Initialization: Make sure that your form is properly initialized before you try to patch it. If the form doesn’t exist when you’re calling
patchValue, it won’t be able to set the values.Form Control Names: Ensure that the form control names you’re using in the
patchValuemethod match the ones in your form group.Data Structure: The structure of the data you’re trying to patch needs to match the structure of your form. If you’re trying to patch a nested form group or an array, the data you’re using to patch needs to have the same nested structure.
Here’s a way to ensure that the data is available before patching the form:
This will check if
editdatais defined and if it has at least one item before trying to patch the form. If the data isn’t available, it won’t try to patch the form and skip over the block.manikandan rPosted Jan 19, 2024, 6:34 AM
Hi @naimish,
Yes it is asynchronous api call. I modified code as below. this.editdata.length is 1. Still pathValue is getting skipped and form control is empty
setpopupdata(project_Id: any) {
this.service.getReportsbyId(project_Id).subscribe(item => {
this.editdata = item;
if (this.editdata && this.editdata.length > 0) {
this.editForm.patchValue({
projectId: this.editdata[0].projectId
});
}