我有一个mat-autocomplete组件,其中的选项将在用户输入时从服务调用中填充(部分搜索):
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="areaSelected($event.option.value)">
<mat-option *ngFor="let option of options" [value]="option">{{ option }}</mat-option>
</mat-autocomplete>
在我的TS代码中,当用户选择一个值时,我在处理结束时将选项数组设置为空数组:
resetFetchedOptions() {
this.options = [];
}
其工作原理是调用代码,并将this.options设置为空数组。问题是,当用户尝试在字段中键入另一个值时,以前的选项仍然存在。如果他们输入,选项将被清除,基于部分搜索的新选项将被填充,所以我认为这是一个渲染问题,但我对Angular材质有点陌生,所以我不确定这是错误的方法还是我错过了一个步骤。
谢谢!
发布于 2019-09-04 18:45:53
你使用的是反应式表单吗?我做了一个类似的东西(based on this article);
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>Typescript
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;
}发布于 2019-09-04 18:30:51
我认为这是因为您保留了对原始数组的引用,请尝试使用this.options.length=0而不是= []
https://stackoverflow.com/questions/57786476
复制相似问题