Reputation: 3072
I'm building a form like so:
actions = [
{ id: 'walkTo', name: 'Walk To' },
{ id: 'use', name: 'Use' },
{ id: 'give', name: 'Give' },
{ id: 'pickUp', name: 'Pick Up' }
];
this.myForm = this.fBuilder.group({
name: [null, [Validators.required]],
age: [null, [Validators.required]],
actions: this.buildActions(this.actions)
});
But how can I add a control without a key to the formarray that's being built by the buildActions
method. The reason I'm doing it this way, is that the array will be a list of checkboxes
buildActions(arr)
{
var resultArr = [];
arr.forEach((x, index) => {
resultArr.push(this.fBuilder.group({
this.fBuilder.addControl(false)
}))
});
return this.fBuilder.array(resultArr);
}
It errors at the this.fBuilder.addControl(false)
part.
Upvotes: 0
Views: 28
Reputation: 13515
It's erroring because FormBuilder.addControl()
isn't a function.
To build a simple form array, pass in an array of form controls like this:
buildActions(arr): FormArray {
const controls = arr.map(x => this.fBuilder.control(x));
return this.fBuilder.array(controls);
}
It's also possible to nest form groups in a form array if you want to build a more complex form:
buildActions(arr): FormArray {
const groups = arr.map(x => this.fBuilder.group({
text: this.fBuilder.control(x.text),
checked: this.fBuilder.control(x.checked)
}));
return this.fBuilder.array(groups);
}
DEMO: https://stackblitz.com/edit/angular-tpcpzc
Upvotes: 1