Frank
Frank

Reputation: 2431

Angular Autocomplete Object

I am battling to understand how to use the Angular Material Autocomplete when using an object. I basically followed the Angular Docs and just replaced the options array with an options object, but I'm not sure how to get it to work. Mind having a look here? I will delete the question if it has many answers elsewhere.

Here are my html and ts components. All the imports and everything is definitely correct so I am not showing any of that.

<mat-form-field>
  <input matInput [formControl]="myControl" [matAutocomplete]="auto">
  <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
      {{ option }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

  ###############################

  myControl: FormControl = new FormControl();
  filteredOptions: Observable<string[]>;

  options = [
    {color: 'One'},
    {color: 'Two'},
    {color: 'Three'},
  ];

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

  filter(val: string): string[] {
    return this.options.filter(option =>
      option.toLowerCase().includes(val.toLowerCase()));
  }

Upvotes: 4

Views: 9156

Answers (1)

bugs
bugs

Reputation: 15313

You are almost there, you only need to map your array to the inner properties of your objects. This is necessary as the return value of your filter function is an array of strings.

filter(val: string): string[] {
  return this.options.map(x => x.color).filter(option =>
    option.toLowerCase().includes(val.toLowerCase()));
}

Demo

Upvotes: 7

Related Questions