Angular2材质自动完成对象数组的自定义过滤器

时间:2017-12-12 10:39:41

标签: angular filter autocomplete

有关于如何为自动完成数组使用自定义过滤器的https://material.angular.io/components/autocomplete/overview文档

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

有没有办法过滤对象数组,并按某些属性过滤(例如id和cat)?

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

3 个答案:

答案 0 :(得分:3)

以下代码适用于我:

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));
    }
}

这是您的HTML模板:

<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>

答案 1 :(得分:1)

你应该尝试这一点肯定会有效:

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

filter(val) {
   if(this.contacts){
   return this.options.filter(option=>
    option.cat.toLowerCase().includes(val.toLowerCase()));
  }
}

你的html模板:

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

答案 2 :(得分:0)

检查此解决方案:

 <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn.bind(this)">
  <mat-option *ngFor="let option of filteredOptions | async" [value]="option.id" 
  (onSelectionChange)="updateMySelection(option.id)">
    {{option.nombre}}
  </mat-option>
</mat-autocomplete>

*.ts

Demo