Reputation: 2945
I have a reactive form in my angular application, and I'm trying to submit a form that includes an array.
In my ngOnInit() I populate the form as follows:
this.userForm = this.fb.group({
id: [result.id, Validators.required],
firstName: [result.firstName, Validators.required],
lastName: [result.lastName, Validators.required],
roles: this.fb.array([])
});
When submitting the form, I'm trying to add the contents on a string array into my form.
I'm adding my string array to the form like this:
this.userForm.controls.roles = this.roles.filter(x=>x.selected == true).map(x=>x.name)
This seems to work:
console.log(this.userForm.controls.roles)
gives me:
["Administrator", "Manager"]
However when I check the contents of my userForm (which is what I'm submitting), roles is blank:
console.log(this.userForm.value)
firstName: "John"
id: "4efba5d3-1875-4496-aeca-6f372924a700"
lastName: "Smith"
roles: []
What am I doing wrong?
Upvotes: 0
Views: 36
Reputation: 14679
Don't
this.userForm.controls.roles = this.roles.filter(x=>x.selected == true).map(x=>x.name)
instead, do
this.userForm.patchValue(
{ roles: this.roles.filter(x=>x.selected == true).map(x=>x.name) }
);
Upvotes: 1
Reputation: 109
try to use this.userForm.patchValue({roles: this.roles.filter(x=>x.selected == true).map(x=>x.name)})
instead of changing the controls of the form.
Upvotes: 3