【问题标题】:mat-autocomplete: Prevent displaying the old listmat-autocomplete:防止显示旧列表
【发布时间】:2019-10-23 21:30:11
【问题描述】:

使用以下脚本,我可以添加<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 秒后它消失并显示新列表。

可能需要时间,因为需要从服务器发送新数据。但是我怎样才能让它只显示新列表呢?

【问题讨论】:

    标签: angular typescript angular-material


    【解决方案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() 来获取它)。

    【讨论】:

    • 感谢您的回答,但我收到以下错误:TS2345: Argument of type 'MatAutocomplete' is not assignable to parameter of type 'FromEventTarget&lt;unknown&gt;'. Property 'length' is missing in type 'MatAutocomplete' but required in type 'ArrayLike&lt;EventTargetLike&lt;unknown&gt;&gt;'. 我的 ViewChild 看起来像这样:@ViewChild('auto', {static: false}) matAutocomplete: MatAutocomplete;
    • 添加了 @ViewChild 装饰器,以定位 ElementRef。然后在fromEvent中使用nativeElement属性作为目标
    • 我也尝试过同样的错误:TS2345: Argument of type 'ElementRef&lt;any&gt;' is not assignable to parameter of type 'FromEventTarget&lt;unknown&gt;'. Property 'length' is missing in type 'ElementRef&lt;any&gt;' but required in type 'ArrayLike&lt;EventTargetLike&lt;unknown&gt;&gt;'.
    • 您是否从'@angular/core 导入ElementRef 并从rxjs 导入fromEvent
    • Rxjs 6+ 版本的导入应该是 - import { ElementRef } from '@angular/core'; import { fromEvent } from 'rxjs';
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 2018-07-06
    • 2020-04-24
    • 2017-03-29
    • 1970-01-01
    • 2018-12-15
    相关资源
    最近更新 更多