user12217822
user12217822

Reputation: 302

Fixed filter bar in mat select in angular 9

I'm using angular 8 and I implement the filter in dropdown fields. But I don't know how can I fix the search bar at the top of the mat select.

stackblitz

html

<h4>mat-select</h4>
<mat-form-field>
  <mat-label>State</mat-label>
  <mat-select>
     <input (keyup)="onKey($event.target.value)"> // **Send user input to TS**
    <mat-option>None</mat-option>
    <mat-option *ngFor="let state of selectedStates" [value]="state">{{state}}</mat-option>
  </mat-select>
</mat-form-field>

ts

states: string[] = [
    'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware',
    'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky',
    'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi',
    'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico',
    'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania',
    'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
    'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
  ];


selectedStates = this.states; 


onKey(value) { 
this.selectedStates = this.search(value);
}


search(value: string) { 
  let filter = value.toLowerCase();
  return this.states.filter(option => option.toLowerCase().startsWith(filter));
}

Upvotes: 0

Views: 977

Answers (1)

Jobelle
Jobelle

Reputation: 2834

You can use ngx-mat-select-search package to achieve the same:

First Install:

npm install ngx-mat-select-search

In app.module.ts:

import { NgxMatSelectSearchModule } from 'ngx-mat-select-search';
and in imports array:

imports: [
   ....,
   NgxMatSelectSearchModule 
]

HTML Code:

<mat-select [formControl]="control" ngDefaultControl placeholder="Tags" #Select>
        <ngx-mat-select-search [placeholderLabel]="'Search Item'" [noEntriesFoundLabel]="'No matching records found'" [formControl]="control"
         ngDefaultControl></ngx-mat-select-search>
        <mat-option class="m-t" *ngFor="let obj of filteredRecords | async" [value]="obj">
            {{obj}}
        </mat-option>
    </mat-select>

CheckThisSample

Upvotes: 1

Related Questions