Reputation: 1795
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
Upvotes: 2
Views: 3311
Reputation: 449
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));
}
}
Upvotes: 2
Reputation: 214305
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]: ['']
^^^^^
});
}
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
Upvotes: 4