How to set dynamic value to formControl in angular 7

I have answered a similar question here which have a better explanation with examples.

Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances.

patchValue does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls. On the other hand, setValue requires all Form Control values to be filled in, and it will return an error if any of your controls are not specified within the parameter.

In this scenario, we will use patchValue to update the values in userForm.

If the properties in TemplateJson is the same as the FormControlNames, you can simple do it this way:

this.userForm.patchValue(this.data) 

If the names are different,

this.userForm.patchValue({
  property1: this.data.bbb
  property2: this.data.aaa
  .
  .
}) 

I had a similar issue where I tried to use 'setValues' with 'this.class.attribute' after my subscribe and I had a "cannot read value of undefined" error. It turned out you have to use the setValue inside the subscribe.

 //My Get method
 getX(): void {
    const id = +this._route
    .snapshot.paramMap.get('id');
    this._xService.getX(id)
    
    //Now my subscribe
    .subscribe(x =>  {
      this.x = x;

        //And my setValue inside my subscribe
        this.nameOfYourForm.setValue({
          formAttribute1: this.x.Attribute1,
          //The x attribute should match the name in the API / database and not the name in your class
       })
    })
  }

Hope this help someone.


You can use SetValue method of FormControl:

setValue():

Sets a new value for the form control.

In your case it will be like:

this.userForm.controls['TemplateJson'].setValue(this.data.TemplateJson);

Stackblitz_Demo