Skip to content

Commit

Permalink
docs(material/form-field): add guide for handling unsubscribable erro…
Browse files Browse the repository at this point in the history
…r triggers in custom form field control (#27010)
  • Loading branch information
behzadmehrabi authored Jul 18, 2023
1 parent ad8b880 commit ffffc82
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions guides/creating-a-custom-form-field-control.md
Original file line number Diff line number Diff line change
Expand Up @@ -326,15 +326,51 @@ private _disabled = false;

#### `errorState`

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

```ts
get errorState(): boolean {
return this.parts.invalid && this.touched;
}
```

However, there are some error triggers that we can't subscribe to (e.g. parent form submissions),
to handle such cases we should re-evaluate `errorState` on every change detection cycle.

```ts
/** Whether the component is in an error state. */
errorState: boolean = false;

constructor(
...,
@Optional() private _parentForm: NgForm,
@Optional() private _parentFormGroup: FormGroupDirective
) {
...
}

ngDoCheck() {
if (this.ngControl) {
this.updateErrorState();
}
}

private updateErrorState() {
const parent = this._parentFormGroup || this.parentForm;

const oldState = this.errorState;
const newState = (this.ngControl?.invalid || this.parts.invalid) && (this.touched || parent.submitted);

if (oldState !== newState) {
this.errorState = newState;
this.stateChanges.next();
}
}
```

Keep in mind that `updateErrorState()` must have minimal logic to avoid performance issues.

#### `controlType`

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

0 comments on commit ffffc82

Please sign in to comment.