検証関数では、データが検証され、正常に機能するかどうかを確認するために API に要求を行います。
しかし、値がオブジェクトの場合は null を返しますが、それは mat-autocomplete を壊します (パネルは決して閉じません)。
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Optional, EventEmitter, Output, Self } from '@angular/core';
import { AbstractControl, ControlValueAccessor, NgControl, ValidationErrors } from '@angular/forms';
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { ErrorStateMatcher } from '@angular/material/core';
import { Observable } from 'rxjs';
import { finalize, map } from 'rxjs/operators';
import { PostalArea } from 'src/app/feature/address/postal-area/portal-area.model';
import { PostalAreaService } from 'src/app/feature/address/postal-area/postal-area.service';
@Component({
selector: 'postal-code',
templateUrl: './postal-code.component.html',
styleUrls: ['./postal-code.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class PostalCodeComponent implements ControlValueAccessor {
stateMatcher: ErrorStateMatcher = new CtrlErrorStateMatcher();
postalArea$: Observable<PostalArea[]>;
@Output() onPostalAreaSelected: EventEmitter<PostalArea> = new EventEmitter();
constructor(
private readonly _postalAreaService: PostalAreaService,
private readonly _changeDetectorRef: ChangeDetectorRef,
@Optional() @Self() public ngControl: NgControl,
) {
if (this.ngControl != null) {
// Setting the value accessor directly (instead of using the providers) to avoid running into a circular import.
this.ngControl.valueAccessor = this;
}
}
ngOnInit() {
this.ngControl.control.setAsyncValidators(this.validate.bind(this));
this.ngControl.control.updateValueAndValidity();
}
onTouched = (_value?: any) => { };
onChanged = (_value?: any) => { };
writeValue(val: string): void {
this.ngControl.control?.setValue(val);
}
registerOnChange(fn: any): void {
this.onChanged = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
validate(control: AbstractControl): Observable<ValidationErrors | null> {
if (typeof control.value !== 'string') {
return null;
}
this.postalArea$ = this._postalAreaService.getPostalAreas(control.value);
return this._postalAreaService.getPostalAreas(control.value).pipe(
map(postalArea => {
if (postalArea.length === 0) {
return { invalidPostalCode: true };
} else {
return null;
}
}),
finalize(() => {
this._changeDetectorRef.markForCheck();
})
);
}
displayFn(postalArea?: PostalArea) {
return postalArea ? postalArea.zipCode : '';
}
onSelectionChanged(event: MatAutocompleteSelectedEvent) {
this.onPostalAreaSelected.emit(event.option.value);
}
}
export class CtrlErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: AbstractControl): boolean {
return !!(control && control.invalid && control.touched);
}
}
テンプレート:
<input matInput [errorStateMatcher]="stateMatcher" [formControl]="ngControl?.control"
[matAutocomplete]="postalCodeAutoComplete" (input)="onChanged($event.target.value)" (blur)="onTouched()"
name="postal-code" />
<mat-autocomplete #postalCodeAutoComplete="matAutocomplete" [displayWith]="displayFn.bind(this)"
(optionSelected)="onSelectionChanged($event)">
<mat-option *ngFor="let postalArea of (postalArea$ | async)" [value]="postalArea">
{{ postalArea.zipCode }} {{ postalArea.name }}
</mat-option>
</mat-autocomplete>