Skip to content

Commit ffffc82

Browse files
docs(material/form-field): add guide for handling unsubscribable error triggers in custom form field control (#27010)
1 parent ad8b880 commit ffffc82

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

guides/creating-a-custom-form-field-control.md

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -326,15 +326,51 @@ private _disabled = false;
326326

327327
#### `errorState`
328328

329-
This property indicates whether the associated `NgControl` is in an error state. In this example,
330-
we show an error if the input is invalid and our component has been touched.
329+
This property indicates whether the associated `NgControl` is in an error state. For example,
330+
we can show an error if the input is invalid and our component has been touched.
331331

332332
```ts
333333
get errorState(): boolean {
334334
return this.parts.invalid && this.touched;
335335
}
336336
```
337337

338+
However, there are some error triggers that we can't subscribe to (e.g. parent form submissions),
339+
to handle such cases we should re-evaluate `errorState` on every change detection cycle.
340+
341+
```ts
342+
/** Whether the component is in an error state. */
343+
errorState: boolean = false;
344+
345+
constructor(
346+
...,
347+
@Optional() private _parentForm: NgForm,
348+
@Optional() private _parentFormGroup: FormGroupDirective
349+
) {
350+
...
351+
}
352+
353+
ngDoCheck() {
354+
if (this.ngControl) {
355+
this.updateErrorState();
356+
}
357+
}
358+
359+
private updateErrorState() {
360+
const parent = this._parentFormGroup || this.parentForm;
361+
362+
const oldState = this.errorState;
363+
const newState = (this.ngControl?.invalid || this.parts.invalid) && (this.touched || parent.submitted);
364+
365+
if (oldState !== newState) {
366+
this.errorState = newState;
367+
this.stateChanges.next();
368+
}
369+
}
370+
```
371+
372+
Keep in mind that `updateErrorState()` must have minimal logic to avoid performance issues.
373+
338374
#### `controlType`
339375

340376
This property allows us to specify a unique string for the type of control in form field. The

0 commit comments

Comments
 (0)