你在使用反应形式吗?我做了一个类似的事情(基于这篇文章);
html
<mat-form-field class="width-filler">
<input type="text" matInput placeholder="Search" [matAutocomplete]="auto" [formControl]="formControl" autocomplete="off" autofocus>
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFunc">
<mat-option *ngIf="isSearching" class="is-loading"><mat-spinner diameter="20"></mat-spinner></mat-option>
<mat-option *ngFor="let result of filteredResult" [value]="result">
{{result.description}}
</mat-option>
</mat-autocomplete>
<mat-hint>{{searchHint()}}</mat-hint>
</mat-form-field>
打字稿
ngOnInit() {
this.formControl
.valueChanges
.pipe(
debounceTime(300),
tap(() => this.isSearching = true),
switchMap(value => this.someService.searchStuff<ResultType[]>(this.getSearchString(value as any))
.pipe(
finalize(() => this.isSearching = false),
)
)
)
.subscribe(result => this.filteredResult = result);
this.formControl.valueChanges.subscribe(value => this.setValue(value));
}
// Need to handle both the search string and a selected full type
private setValue(value: string | ResultType) : void {
if (typeof value === "string")
this.selectedValue = null;
else
this.selectedValue = value;
}
private getSearchString(value: string | ResultType) {
if (typeof value === "string")
return value;
else
return value.description;
}