[英]mat-autocomplete: Need to Reset the List of Options After a Selection is Made
我有一个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代码中,我在用户选择值时处理结束时将options数组设置为空数组:
resetFetchedOptions() { this.options = []; }
这样可以调用代码,并将this.options设置为空数组。 问题是,当用户尝试在字段中键入另一个值时,之前的选项仍然存在。 如果他们输入,选项会被清除,并且基于部分搜索的新选项会被填充,所以我认为这是一个渲染问题,但我对Angular Material有点新,所以我不确定这是不是是错误的方法或我错过了一步。
谢谢!
你在使用反应形式吗? 我做了类似的事情( 基于这篇文章 );
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;
}
我认为这是因为您保留对原始数组的引用,请尝试this.options.length=0
而不是= []
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.