Angular material autocomplete not working, no errors shown

22,560

You are missing a filter method in your .ts

You have to subscribe to your myControl valueChanges this way:

this.myControl.valueChanges.subscribe(newValue=>{
    this.filteredValues = this.filterValues(newValue);
})

So everytime your form control value changes you call your custom filterValues() method, that should look like:

filterValues(search: string) {
    return this.testValues.filter(value=>
    value.toLowerCase().indexOf(search.toLowerCase()) === 0);
}

So you use your testValues array as a base array, and your filteredValues array in your html:

<mat-option *ngFor="let n of filteredValues" [value]="n">
    {{n}}
</mat-option>

Filtering is not automatic, you have to use your custom method to filter the options. Hope it helps

Share:
22,560
Simeon Nakov
Author by

Simeon Nakov

Updated on July 09, 2022

Comments

  • Simeon Nakov
    Simeon Nakov almost 2 years

    I've implemented my autocomplete, no errors, everything seems ok however absolutely nothing happens. I enter something in the input field and no action seems to happen, nothing is shown in the console.

    HTML

      <form>
        <mat-form-field>
          <input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto">
        </mat-form-field>
    
        <mat-autocomplete #auto="matAutocomplete">
          <mat-option *ngFor="let n of testValues" [value]="n">
            {{n}}
          </mat-option>
        </mat-autocomplete>
      </form>
    

    TS

    import { MatAutocomplete } from '@angular/material/autocomplete';
    import { FormControl } from '@angular/forms';
    ...
    public testValues = ['one', 'two', 'three', 'four'];
    public myControl: FormControl;
    ...
    constructor() {
        this.myControl = new FormControl();
    }
    

    EDIT: I have imported

    import {MatAutocompleteModule} from '@angular/material/autocomplete';
    

    in my app module.

    Version of material -

    "@angular/material": "^5.0.0-rc.2",
    
  • Simeon Nakov
    Simeon Nakov over 6 years
    Yes, it should work with a filter. Thanks for taking the time, I tried using yours but it gives me 'Cannot find name "startWith"' and 'Cannot find name map'. Am I missing some import here?