Can't set variable as FormControl name when creating Dynamic Reactive Form in Angular

Viewed 3318

I am creating Dynamic Reactive form in Angular. But in the below code level.name is not being accepted as compiler is not allowing to give variable inside the group(). It is only allowing fixed value like - state, city etc instead of level.name variable where level is an object which has name field...

this.countryNextLevelsBeforeMan.forEach(**level** => {
  let l2 =<FormArray> this.l1FormGroup2.controls["l2"]; 
  l2.push(this.formBuilder.group({
    **level.name** : null   --> compilation error on this line as variable not getting allowed
  }))
});

Inside the group method I want to give control name as a variable (level.name). In the for loop if level is {"name" : "State" , "id" : 2} then I want to set it like below,

l2.push(this.formBuilder.group({
        **State** : null    --> No compilation error if we give fixed value
     }))

(Instead of 'State' I want it to be dynamically assigned by level.name as level.name can be City, Street etc)

Please help!!!

3 Answers

Try this:

this.countryNextLevelsBeforeMan.forEach(level => {
  let l2 =<FormArray> this.l1FormGroup2.controls["l2"]; 
  l2.push(this.formBuilder.group({
    [level.name]: null,
    [level.id]: []
  }))
});

SuryaN, if you want to create a FormGroup with "dynamic FormControl name" use the method addControl of a FormGroup. I suggest create a function that return a formGroup from an array of names

getFormGroup(names:string[])
{
   const group=new FormGroup({}) //<---create a formGroup empty
   names.ForEach(x=>{
       group.AddControl(x,new FormControl())
   })
   return group;
}

So you can call the function like

   const group=this.getFormGroup(this.countryNextLevelsBeforeMan.map(x=>x.name))
   //make what ever you want with the FormGroup

Replace the below line as...

level.name

to

level[name]

Related