在 Angular 中的 FormGroup 中循环子 AbstractControl 列表

Looping on child AbstractControl list within FormGroup in Angular

下面是一个组件的代码,它在显示验证错误之前尝试确定 FormGroup 中的每个 AbstractControl 是否为 pristine

export class FieldErrorsComponent {
  @Input() control: AbstractControl | FormGroup;

  public controlsAreNotPristine(): boolean {
    if (this.control instanceof FormGroup) {
      return ((this.control as FormGroup).controls.every(control => !control.pristine));
    }
  }
}

这当然行不通,因为FromGroup.controls定义如下:

controls: { [key: string]: AbstractControl; };

我不知道在 controls 上循环有什么好的选择?真正的问题是 FormGroup.pristine 并没有真正反映其子控件总和的值,我理解这可能是设计使然。

FormGroup 没有像 can be seen from its interface 那样提供任何迭代器。但它提供了对如下定义的控件的访问:

controls: {[key: string]: AbstractControl}

因此您可以使用标准 for in 循环来迭代它们:

  public controlsAreNotPristine(): boolean {
    if (this.control instanceof FormGroup) {
      const controls = (this.control as FormGroup).controls
      for (const name in controls) {
         if (controls[name].pristine) {
            return true;
         }
      }
       return false;
    }
  }

The real problem is that FormGroup.pristine does not really reflect the value of the sum of its child controls, which I understand might be made so by design.

FormGroup 应正确反映其子控件的状态。这个可以从FormGroup上的_updatePristine方法看出:

  _updatePristine(opts: {onlySelf?: boolean} = {}): void {
    this._pristine = !this._anyControlsDirty(); <------- ensure all controls are pristine

    if (this._parent && !opts.onlySelf) {
      this._parent._updatePristine(opts);
    }
  }