Looping over child list AbstractControl in FormGroup in Angular
Here's the component code that tries to determine if each is AbstractControl
inside FormGroup
pristine
before displaying the validation error:
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));
}
}
}
This of course doesn't work because it FromGroup.controls
is defined like this:
controls: { [key: string]: AbstractControl; };
I don't know what a good loop alternative controls
would be? The real problem is that FormGroup.pristine
it doesn't really reflect the value of the sum of its child controls, which I understand can be done by design.
source to share
FormGroup
does not provide any iterator as seen from its interface . But it does provide access to controls that are defined like this:
controls: {[key: string]: AbstractControl}
So, you can use a standard loop for in
to iterate over them:
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 the FormGroup.pristine doesn't really reflect the value of the sum of its child controls, which I understand can do this by design.
The FormGroup must correctly reflect the state of its child controls. This can be seen from the method _updatePristine
in the FormGroup:
_updatePristine(opts: {onlySelf?: boolean} = {}): void {
this._pristine = !this._anyControlsDirty(); <------- ensure all controls are pristine
if (this._parent && !opts.onlySelf) {
this._parent._updatePristine(opts);
}
}
source to share