Patch the values in angular form

3967 views javascript
-2

I am making an application using angular 6, where i am using angular dynamic form.

As of creating the form and submitting i have completed everything, You could able to see the working stackblitz, https://stackblitz.com/edit/angular-x4a5b6-hne6fg

FYI: This form has children elemts which will gets opened and also gets append on click the add button and removes one by last on click the remove button..

The thing i am in the need is, i just need to patch the values to each inputs via service during edit of each row respectively..

Say i call the get service as,

    this.dynamicFormService.getRest(url,token).subscribe(res => {
        this.form.value = res.data;   //Tried this line but got error (Cannot assign to 'value' because it is a constant or a read-only property)
     })

I am trying to patch the values to the form which you can see in dynamic-form.ts in stacblitz,

  ngOnInit() {
    this.form = this.qcs.toFormGroup(this.questions);
}

If i console the the form as console.log(this.form.value), it gives the result as,

template_desc: ""
template_name: ""
template_properties: Array(0)
length: 0
__proto__: Array(0)

And console.log(res.data) in get service result gives,

data:
template_obj_id: "123"
template_desc: "New template description"
template_name: "New Template"
template_properties: Array(1)
0:
property_name: "Property name"
property_origin: ["VBM"]
property_required: true
property_type: "Property type"

I just need to bind this data that comes from res.data to get patched to all the form inputs.

You can also take these values as static and bind it to the form inputs.. Because these are the values i need to patch to all the inputs respectively like template_name has the value as New Template and template_desc as New template description etc..

Though the question went little bigger for explanation, the thing i am in the need is single.. I need to patch the data comes from service (res.data) to each form elements respectively.

This get service is called for editing the particular element so kindly give me solution as patching the value instead of making default "value : "some value"

Kindly help to achieve the patching of data to the form elements...

answered question

1 Answer

6

Use patchValue to set the data to form

this.dynamicFormService.getRest(url,token).subscribe(res => {
   this.form.patchValue({
      template_desc: res.data.template_desc,
      template_name:  res.data.template_name,
    });
 }

posted this

Have an answer?

JD

Please login first before posting an answer.