Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set dynamic value to formControl in angular 7

I have a 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!

like image 873
Ronak Dumaniya Avatar asked Apr 12 '19 05:04

Ronak Dumaniya


People also ask

How do I set default value in FormControl?

1. Default Value. If we want to set a default value to our form control, we can pass a default value while instantiating a FormControl in our class. city = new FormControl('Noida'); married = new FormControl(true);


1 Answers

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

like image 182
Prashant Pimpale Avatar answered Sep 28 '22 16:09

Prashant Pimpale