Search code examples
angularmat-autocompleteangular8

How to set filter with mat auto select in angular template driven form


How to set filter with mat auto select in angular template driven form.

<mat-form-field class="pl">
    <input matInput name="item_id" 
    [(ngModel)]="stock.item_id" 
    #item_id="ngModel" 
    placeholder="Item"           
    [matAutocomplete]="auto" required>
    <mat-autocomplete #auto="matAutocomplete" [displayWith]="valueMapper">
        <mat-option *ngFor="let item of itemsData" [value]="item.id">
        {{item.text}}
        </mat-option>
    </mat-autocomplete>
</mat-form-field>

Please see stackblitz example: click here


Solution

  • you can use ngModelChange event to capture changes in the autocomplete input and use that event to filter your items array.

    <input matInput name="item_id" [(ngModel)]="selected_item_id" #item_id="ngModel"
        placeholder="Item" [matAutocomplete]="auto" required
        (ngModelChange)="applyFilter($event)">
    

    here is the working demo:

    https://stackblitz.com/edit/angular8-material8-select-and-autoselect-ett7id