Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 material autocomplete custom filter for array of objects

There are https://material.angular.io/components/autocomplete/overview documentation of how to use custom filter for autocomplete array

options = [
    'One',
    'Two',
    'Three'
  ];

Is there a way how to filter for array of objects, and filter by some properties (by id and cat for example)?

 options = [
        {"id":1,"name":"colour","cat":"red"},
        {"id":2,"name":"colour","cat":"blue},
        {"id":3,"name":"colour","cat":"green"}
      ];
like image 239
Serhio g. Lazin Avatar asked Dec 11 '22 08:12

Serhio g. Lazin


1 Answers

Following code works for me:

import { Component, OnInit } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';

@Component({
    moduleId: module.id,
    selector: 'my-app',
    templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {

    myForm: FormControl;
    filteredOptions: Observable<any[]>;

    options: any[] = [
        { "id": 1, "name": "colour", "cat": "red" },
        { "id": 2, "name": "colour", "cat": "blue" },
        { "id": 3, "name": "colour", "cat": "green" }
    ];

    ngOnInit(): void {

        this.myForm = new FormControl();
        this.filteredOptions = this.myForm.valueChanges
            .startWith(null)
            .map(term => this.findOption(term));

    }


    findOption(val: string) {

        return this.options.filter((s) => new RegExp(val, 'gi').test(s.cat));
    }
}

And this is your HTML template:

<form class="example-form">
  <mat-form-field>
    <input matInput placeholder="Choose option" [formControl]="myForm" [matAutocomplete]="auto" />
  </mat-form-field>

  <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let item of filteredOptions | async" [value]="item">
      <div>{{item.cat}}</div>
    </mat-option>
  </mat-autocomplete>
</form>
like image 138
armache Avatar answered Dec 27 '22 07:12

armache