Skip to content
Advertisement

Don’t show blank record on autocomplete in Angular

I have this autocomplete in Angular

<input type="text" matInput [ngModel]="List" #searchInput [matAutocomplete]="autocopmlete" (focus)="filter('')"
      (ngModelChange)="filter($event)">
    <mat-autocomplete #autocopmlete="matAutocomplete" [displayWith]="Name">
      <mat-option *ngFor="let item of filteredObject" [value]="item" (onSelectionChange)="selectUser($event,item)"
        (click)="searchInput.value=''">
        {{ item.Name }} 
      </mat-option>
    </mat-autocomplete>

we use this filter function

 filter(value = '') {
    if (typeof value !== 'string' || typeof value === 'undefined' || typeof this.chatList==='undefined') {
        return;
    }
    this.filteredObject = this.chatList.filter(
        a => ~a.Name.toLocaleLowerCase().indexOf(value.toLocaleLowerCase()))
    );
  }

but issue is if i get those records also where Name is blank how should i remove that blank record from result.

Advertisement

Answer

You would need to add an additional check in the filter function, where you can check if Name property exist on object !!a.Name

this.filteredObject = this.chatList.filter(
    a => (
      !!a.Name &&
      ~a.Name.toLocaleLowerCase().indexOf(value.toLocaleLowerCase())
    )
);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement