Skip to content

docs(material/form-field): fix handling of error state in the custom … #22782

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 22 additions & 13 deletions guides/creating-a-custom-form-field-control.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,23 +227,30 @@ For additional information about `ControlValueAccessor` see the [API docs](https
This property indicates whether the form field control should be considered to be in a
focused state. When it is in a focused state, the form field is displayed with a solid color
underline. For the purposes of our component, we want to consider it focused if any of the part
inputs are focused. We can use the `FocusMonitor` from `@angular/cdk` to easily check this. We also
need to remember to emit on the `stateChanges` stream so change detection can happen.
inputs are focused. We can use the `focusin` and `focusout` events to easily check this. We also
need to remember to emit on the `stateChanges` when the focused stated changes stream so change
detection can happen.

In addition to updating the focused state, we use the `focusin` and `focusout` methods to update the
internal touched state of our component, which we'll use to determine the error state.

```ts
focused = false;

constructor(fb: FormBuilder, private fm: FocusMonitor, private elRef: ElementRef<HTMLElement>) {
...
fm.monitor(elRef, true).subscribe(origin => {
this.focused = !!origin;
onFocusIn(event: FocusEvent) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

optional: my preference would be to name these methods something that reflects what they do, but I don't feel super strongly since it's an example

if (!this.focused) {
this.focused = true;
this.stateChanges.next();
});
}
}

ngOnDestroy() {
...
this.fm.stopMonitoring(this.elRef);
onFocusOut(event: FocusEvent) {
if (!this._elementRef.nativeElement.contains(event.relatedTarget as Element)) {
this.touched = true;
this.focused = false;
this.onTouched();
this.stateChanges.next();
}
}
```

Expand Down Expand Up @@ -319,11 +326,13 @@ private _disabled = false;

#### `errorState`

This property indicates whether the associated `NgControl` is in an error state. Since we're not
using an `NgControl` in this example, we don't need to do anything other than just set it to `false`.
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.

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

#### `controlType`
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<div role="group" class="example-tel-input-container"
[formGroup]="parts"
[attr.aria-labelledby]="_formField?.getLabelId()">
[attr.aria-labelledby]="_formField?.getLabelId()"
(focusin)="onFocusIn($event)"
(focusout)="onFocusOut($event)">
<input class="example-tel-input-element"
formControlName="area" size="3"
maxLength="3"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export class MyTelInput
parts: FormGroup;
stateChanges = new Subject<void>();
focused = false;
touched = false;
controlType = 'example-tel-input';
id = `example-tel-input-${MyTelInput.nextId++}`;
onChange = (_: any) => {};
Expand Down Expand Up @@ -130,7 +131,7 @@ export class MyTelInput
}

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

constructor(
Expand All @@ -155,19 +156,32 @@ export class MyTelInput
]
});

_focusMonitor.monitor(_elementRef, true).subscribe(origin => {
if (this.focused && !origin) {
this.onTouched();
}
this.focused = !!origin;
this.stateChanges.next();
});

if (this.ngControl != null) {
this.ngControl.valueAccessor = this;
}
}

ngOnDestroy() {
this.stateChanges.complete();
this._focusMonitor.stopMonitoring(this._elementRef);
}

onFocusIn(event: FocusEvent) {
if (!this.focused) {
this.focused = true;
this.stateChanges.next();
}
}

onFocusOut(event: FocusEvent) {
if (!this._elementRef.nativeElement.contains(event.relatedTarget as Element)) {
this.touched = true;
this.focused = false;
this.onTouched();
this.stateChanges.next();
}
}

autoFocusNext(control: AbstractControl, nextElement?: HTMLInputElement): void {
if (!control.errors && nextElement) {
this._focusMonitor.focusVia(nextElement, 'program');
Expand All @@ -180,11 +194,6 @@ export class MyTelInput
}
}

ngOnDestroy() {
this.stateChanges.complete();
this._focusMonitor.stopMonitoring(this._elementRef);
}

setDescribedByIds(ids: string[]) {
const controlElement = this._elementRef.nativeElement
.querySelector('.example-tel-input-container')!;
Expand Down