angularangular-reactive-formsangular-controllerformarray

How to create formControlName dynamically in Angular 4?


I want to create formControlName dynamically, here is my code in component,

CONTROLER CODE

ngOnInit() {
  this.rForm = this.fb.group({
     question_type_id: this.fb.array([]),
  });

  for (let i = 0; i < this.getQuestionsType.length; i++) {
     const control = <FormArray>this.rForm.controls['question_type_id'];
     control.push(this.initAddress(i));
  }
}

initAddress(i) {
  var ans = "is_answer_"+i;

  return this.fb.group({
    ans: ['']
  });
}

So I want formControlName Like this,

is_answer_0
is_answer_1
is_answer_2

Solution

  • In es6 objects can be created with computed keys. So let's use it:

    initAddress(i) {
      var ans = "is_answer_" + i;
    
      return this.fb.group({
        [ans]: ['']
        ^^^^^
      });
    }
    

    Ng-run Example

    You should be aware that if typescript has target es5 then it will be tranpiled to something like:

    var controlConfig = {};
    controlConfig[ans] = [''];
    

    So it's your second option to go