gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:30:57 24 4
gpt4 key购买 nike

下面是一个组件的代码,它在显示验证错误之前尝试确定 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 并没有真正反射(reflect)其子控件总和的值,据我所知,这可能是设计使然。

最佳答案

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 应该正确反射(reflect)其子控件的状态。从 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);
}
}

关于javascript - 在 Angular 的 FormGroup 中循环子 AbstractControl 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45209841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com