角反应形式不填充新数组

时间:2019-04-03 20:47:36

标签: angular

我的angular应用程序中有一个反应式表单,我正在尝试提交一个包含数组的表单。

在我的ngOnInit()中,如下填写表格:

  this.userForm = this.fb.group({
    id: [result.id, Validators.required],
    firstName: [result.firstName, Validators.required],
    lastName: [result.lastName, Validators.required],
    roles: this.fb.array([])
  });

提交表单时,我正在尝试将字符串数组中的内容添加到表单中。

我正在将字符串数组添加到如下形式:

this.userForm.controls.roles = this.roles.filter(x=>x.selected == true).map(x=>x.name)

这似乎可行:

console.log(this.userForm.controls.roles)

给我:

["Administrator", "Manager"]

但是,当我检查userForm的内容(这是我要提交的内容)时,角色为空白:

console.log(this.userForm.value)

firstName: "John"
id: "4efba5d3-1875-4496-aeca-6f372924a700"
lastName: "Smith"
roles: []

我在做什么错了?

2 个答案:

答案 0 :(得分:3)

尝试使用this.userForm.patchValue({roles: this.roles.filter(x=>x.selected == true).map(x=>x.name)})而不是更改表单的控件。

答案 1 :(得分:1)

不要

this.userForm.controls.roles = this.roles.filter(x=>x.selected == true).map(x=>x.name)

相反,做

this.userForm.patchValue(
   { roles: this.roles.filter(x=>x.selected == true).map(x=>x.name) }
);