1

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!!!

Chellappan வ
  • 18,942
  • 3
  • 21
  • 52
SuryaN
  • 341
  • 1
  • 3
  • 13

3 Answers3

7

Try this:

this.countryNextLevelsBeforeMan.forEach(level => {
  let l2 =<FormArray> this.l1FormGroup2.controls["l2"]; 
  l2.push(this.formBuilder.group({
    [level.name]: null,
    [level.id]: []
  }))
});
Chellappan வ
  • 18,942
  • 3
  • 21
  • 52
  • that's great! it worked, can you tell us why is necessary to use square brackets? – Tecayehuatl Oct 21 '20 at 18:47
  • Thanks ✌ @Tecayehuatl. That's the syntax for generate dynamic key: check this for more Info: https://stackoverflow.com/questions/19837916/creating-object-with-dynamic-keys – Chellappan வ Oct 23 '20 at 08:35
1

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
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Eliseo
  • 39,135
  • 4
  • 22
  • 51
0

Replace the below line as...

level.name

to

level[name]

surendra kumar
  • 1,552
  • 9
  • 15