2

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

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

Try code below. It certainly works !

ngOnInit() {
  for(var i = 0; i < this.getQuestionsType.length; i++) {
    <FormArray>this.rForm.get('question_type_id').push(new FormControl("is_answer_"+i));
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.