angular - 如何在不触发表单更改事件的情况下将 FormGroup 添加到 FormArray

标签 angular

我用 definitionProperties 中的任何空数组初始化一个表单我该如何更新 FormGroup ?我需要这样做而不触发更改事件,否则会导致 valueChanges 中的无限循环可观察的。

this.gridProcessorForm = this.fb.group({
    propertiesSide: new FormControl(),
    objectNamesSide: new FormControl(),
    definitionProperties: this.fb.array([])
});

这会导致无限循环:
this.gridProcessorForm.valueChanges.subscribe(val => {
    let propertyGroups: FormGroup[] = [];
    for (let property of this.objectDefinition.properties) {
      let group = this.createPropertyFormGroup(property);
      (this.gridProcessorForm.get('definitionProperties') as FormArray).push(group); // triggers change event so infinite loop
    }
});

当 setValue 与 { emitEvent: false } 一起使用时覆盖 FormArray 会出错。
this.gridProcessorForm.valueChanges.subscribe(val => {
  if (this.gridSideSelection = 'top') {        
    let propertyGroups: FormGroup[] = [];
    for (let property of this.objectDefinition.properties) {
      let group = this.createPropertyFormGroup(property);
      propertyGroups.push(group);
    }

    (this.gridProcessorForm.get('definitionProperties') as FormArray).setValue(propertyGroups, { emitEvent: false });
  }
});

我收到此错误:
There are no form controls registered with this array yet. 

似乎需要表单构建器使用 FormArray 中的组进行初始化?但我想用所有内容初始化表单。

最佳答案

angular 的 repo 中存在问题。请引用此评论 https://github.com/angular/angular/issues/23336#issuecomment-543209703
基本上,你需要这样做:

const addedControl = new FormControl();
this.controlArray.controls.push(addedControl);
this.controlArray['_registerControl'](addedControl);
更新 05.2021
这已在 Angular v12 https://github.com/angular/angular/issues/20439#issuecomment-779988084 中得到修复

关于angular - 如何在不触发表单更改事件的情况下将 FormGroup 添加到 FormArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58481064/

相关文章:

angular - 如何在 Angular 2 中将方法从一个组件调用到另一个组件?

angular - ngx-select-dropdown 示例值未绑定(bind)

javascript - 如何使用angular material api服务?

angular - 如何在 Angular 4 中使用 "offsetWidth"等 JS 属性

angular - 使用 primeng 日历将样式应用于特定日期

javascript - 如何从 Protractor 中的表中收集和返回聚合数据作为数组?

javascript - 我能知道一种在不提交 Angular 8 表单中的 "Confirm-Password"字段的情况下向 Firebase 提交数据的方法吗?

javascript - Angular 4 平均堆栈 : How to get a value depending on another {{value}}

angular - rxjs/运营商 : can not find module

javascript - 如何在调用同一事件的同时保持一个事件