@@ -326,15 +326,51 @@ private _disabled = false;
326
326
327
327
#### ` errorState `
328
328
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.
331
331
332
332
``` ts
333
333
get errorState (): boolean {
334
334
return this .parts .invalid && this .touched ;
335
335
}
336
336
```
337
337
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
+
338
374
#### ` controlType `
339
375
340
376
This property allows us to specify a unique string for the type of control in form field. The
0 commit comments