从formArray

时间:2018-04-18 00:14:07

标签: javascript angular

我有一个formArray设置,如

在构造函数中:

this.createUserFormList = this.fb.group({
      items: this.fb.array([])
    });

在ngOnInit中:

(<FormArray>this.createUserFormList.controls['items'])
  .push(this.fb.group({
    createName: new FormControl("", [
      Validators.required,
      Validators.minLength(3)
    ]),
    createEmail: new FormControl("", [
      Validators.required,
      Validators.email
    ]),
    createOrganisation: new FormControl("", [
      Validators.required
    ]),
    createRole: new FormControl("", [
      Validators.required
    ])
  }))

用户可以向阵列添加更多组,这可以正常工作,但现在我需要它们才能被删除。

我已尝试过以下方式,但无法正常工作:

removeUserForm(index) {
  this.createUserFormList.controls['items'].value.splice(index, 1);
  //this seem to remove from array when logging however the view does not update
}

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您应该通过removeAt(index) formarray本身中删除项目。

removeUserForm(index) {
  (<FormArray>this.createUserFormList.controls['items']).removeAt(index);
}

参见 details demo