Reza Saadati
Reza Saadati

Reputation: 1274

mat-autocomplete: Prevent displaying the old list

With the following script I am able to add <mat-option> tags:

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;
            }
          });
      }

The problem

If I press a key, I'll get a list of options. If I press another key, the same list (array technologies) will be displayed and after about 1 second it disappears and the new list will be shown.

Maybe it needs time, because the new data needs to be sent from the server. But how can I make it display ONLY the new list?

Upvotes: 0

Views: 560

Answers (1)

Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

Yes, new list wont be shown until data has arrived. You can set this.technologies to an empty array, etc..

And you have two streams here - API call and keyup events. Better merge them into one to have more control on it and the implement other features easier (f.ex. debounceTime, loading animation etc.):

@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;
  }
})

Must use that in ngAfterViewInit(), to grab reference to this.matAutocomplete (and of course, use @ViewChild() for it).

Upvotes: 1

Related Questions