How to set dynamic value to formControl in angular 7

Ronak Dumaniya picture Ronak Dumaniya · Apr 12, 2019 · Viewed 25.1k times · Source

I have drag and drop formBuilder we can able to create form using drag and drop so now i am facing problem i have hidden field in html which is TempleteJson.

Here is html code

 <form [formGroup]="userForm" (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label>Form Name:</label>
      <input type="text" class="form-group" formControlName="TemplateName" />
    </div>
    <div class="form-group">
      <input type="hidden" class="form-group" formControlName="TemplateJson" />
    </div>
    <div class="form-group">
      <label>CreatedOn:</label>
      <input type="date" class="form-group" formControlName="CreatedOn" />
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>

Here is component.ts file

  formBuilder: any;
  formData: any;
  data: any;
 ngOnInit() {
    var id = this.route.snapshot.paramMap.get('id');

    this.dataService.GetFormById(+id).subscribe(response => {
      this.data = response['TemplateJson'];
      this.generateForm();
    },
      err => {
        this.generateForm();
      });

    initJq();
  }

userForm = new FormGroup({
    TemplateName: new FormControl(),
    TemplateJson: new FormControl(),
    CreatedOn: new FormControl(),
  });

 onSubmit() {
    console.log(this.userForm.value);
    this.dataService.addFormTemplate(this.userForm.value);
  }

Now in this.data i have json and that json i want to set in TemplateJson FormControl so how can i do it .

Thank you!

Answer

Prashant Pimpale picture Prashant Pimpale · Apr 12, 2019

You can use SetValue method of FormControl:

setValue():

Sets a new value for the form control.

So you can use it like:

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

Stackblitz_Demo