Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular material autocomplete not working, no errors shown

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",
like image 854
Simeon Nakov Avatar asked Jan 19 '18 08:01

Simeon Nakov


1 Answers

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

like image 67
Gianluca Paris Avatar answered Oct 22 '22 11:10

Gianluca Paris