0

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?

1
  • You are assigning an array or strings (["Administrator", "Manager"]) to an array of AbstractControl. Commented Apr 3, 2019 at 21:00

2 Answers 2

3

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.

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

Comments

1

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) }
);

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.