angular - 如何创建空的formarray

标签 angular

我想创建一个 formarray 这样我就可以稍后推送元素。

我知道我可以使用“criterias.controls.length = 0;”来做这样的事情在声明 FormArray 之后,但我正在寻找一种方法来创建长度为 0 的 formArray 作为声明的一部分。

criterias = new FormArray([]);
criterias.controls.length = 0;
values.forEach(item => {
    criterias.controls.push(new FormGroup({
      'type': new FormControl(item.type, Validators.required),
      'criteria': new FormControl(item.criteria, Validators.required)
    }));
  });

最佳答案

您可以使用表单构建器类来帮助您创建响应式(Reactive)表单

    this.baseForm = this.fb.group({
        criterias: this.fb.array([])
    })

如果您有一个返回表单数组的方法也很好
get criterias(): FormArray {
    return this.baseForm.get("criterias") as FormArray
}

基于此,您可以创建添加方法和删除方法
  addCriteria() {
    this.criterias.push(this.fb.group({

     }))
  }

  removeCriteria(index) {
      this.criterias.removeAt(index)
  }

关于angular - 如何创建空的formarray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48992273/

相关文章:

angular - 我如何使用从一个解析器到另一个解析器的传递数据

angular-oauth2-oidc 忘记密码流程

angular - SQLite 与 ionic 4?无法读取未定义类型错误 : Cannot read property 'then' of undefined 的属性 'then'

angular - Bamboo - Angular 4 应用程序如何部署

angular - 如何使 NativeScript-Angular 应用程序在后台运行?

python - 为了允许非 dict 对象被序列化,将 safe 参数设置为 False

angularjs - Angular 2 ng-需要

javascript - 使用 *ngIf 仅更改相同内容周围的 div

Angular + Ngrx : best practice to select a value in component and in function

Azure 页面重新加载时出现 Angular 网站问题