使用以下脚本,我可以添加<mat-option>
标签:
HTML
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
<mat-option (onSelectionChange)="onEnter($event)" *ngFor="let data of technologies" [value]="data.technology">
<span matBadge="{{data.counter}}" matBadgeOverlap="false">{{data.technology}} </span>
</mat-option>
</mat-autocomplete>
TS
// On Key up, show technologies
onKeyUp(event: any): void {
if (event.target.value.trim().length > 0) {
this.technologiesService.getTechnologies(event.target.value)
.subscribe(data => {
if (JSON.stringify(this.technologies) !== JSON.stringify(data)) {
this.technologies = data;
}
});
}
问题
如果我按一个键,我会得到一个选项列表。如果我按另一个键,将显示相同的列表(数组technologies
),大约1秒钟后它消失,并显示新列表。
也许需要时间,因为新数据需要从服务器发送。但是如何使它仅显示新列表?
答案 0 :(得分:1)
是的,直到数据到达,才会显示新列表。您可以将this.technologies
设置为空数组,等等。
这里有两个流-API调用和keyup事件。更好地将它们合并为一个,以便对其具有更多控制权,并更轻松地实现其他功能(例如debounceTime,加载动画等):
@ViewChild('auto', {static: false}) matAutocomplete: ElementRef<HTMLInputElement>;
fromEvent(this.matAutocomplete.nativeElement, 'keyup').pipe(
switchMap(event => {
this.technologies = [];
return this.technologiesService.getTechnologies(event.target.value)
})
).subscribe(data => {
if (JSON.stringify(this.technologies) !== JSON.stringify(data)) {
this.technologies = data;
}
})
必须在ngAfterViewInit()
中使用该名称,以获取对this.matAutocomplete
的引用(当然,请使用@ViewChild())。