Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()));
  }
like image 753
Frank Avatar asked Oct 19 '25 14:10

Frank


1 Answers

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

like image 88
bugs Avatar answered Oct 22 '25 04:10

bugs