Implement a search filter for the component of angular material

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'
  ];

**// Initially fill the selectedStates so it can be used in the for loop** 
selectedStates = this.states; 

**// Receive user input and send to search method**
onKey(value) { 
this.selectedStates = this.search(value);
}

**// Filter the states list and send back to populate the selectedStates**
search(value: string) { 
  let filter = value.toLowerCase();
  return this.states.filter(option => option.toLowerCase().startsWith(filter));
}

The solution is rather easy.
Should work like a charm 🙂

Leave a Comment

tech