bensalerno
bensalerno

Reputation: 534

Angular material-autocomplete for searches with multiple words?

In my Angular project, I'm using material-autocomplete to search through some of my items. So far, it works as expected.

HTML

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

TS

myControl = new FormControl();
  options: string[] = ['One', 'Two', 'Three'];
  filteredOptions: Observable<string[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(''),
      map(value => this._filter(value))
    );
  }

private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();
   if(filterValue == ''){
      return []
    }
    return this.options.filter(option => option.toLowerCase().indexOf(filterValue) === 0);
  }

This function works, but only for the first word in the search. For example, if you want to search for "Banana Apple", that will autocomplete if you type "B", but it won't autocomplete if you type "Apple." Is there a way to apply this search so that you can search for either word in a multi-word item?

Upvotes: 0

Views: 2549

Answers (1)

Jonathan Lopez
Jonathan Lopez

Reputation: 186

You should change the last line of your _filter method:

return this.options.filter(option => option.toLowerCase().includes(filterValue));

This allows to you to filter finding in all of the value of your option.

Upvotes: 2

Related Questions