Search code examples
angularangular-materialangular2-routingangular13

how to initialize FormGroup when the FormControlName is dynamic and can be changed?


I'm new to angular and I'm facing this case .

in my HTML page a form (formgroup) and inside it i have a div with ngFor directive to loop through an object for whatever time as much needed.

say that I have an input field with formControlName like this :

<input type="text" formControlName="name{{i}}" >

how will I create the FormGroup object in the typescript file ???

In normal case when the controlName is not dynamic I used to do something like this :

this.namedForm = new FormGroup({
   'name': new formControl(),
});

and it works ok ,

but when I add the index to the formControlName how would I create the formGroup object ?

I tried something like this but it is showing error...

let nameControl = 'name'+i;
this.namedForm = new FormGroup({
   nameControl : new formControl(),
});

any help ?


Solution

  • You need add control dynamically like

    this.namedForm.addControl(this.name, new FormControl(''));
    

    See this example: https://angular-ivy-9rbeic.stackblitz.io