对象数组的Angular2材质自动完成自定义过滤器
Posted
技术标签:
【中文标题】对象数组的Angular2材质自动完成自定义过滤器【英文标题】:Angular2 material autocomplete custom filter for array of objects 【发布时间】:2018-05-26 00:23:48 【问题描述】:有 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"
];
【问题讨论】:
嗯,也有这样的样本……material.angular.io/components/autocomplete/… 在这里查看答案 ---> ***.com/questions/48151239/… 【参考方案1】:检查这个解决方案:
<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
【讨论】:
【参考方案2】:你应该试试这个,它肯定会工作:
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>
【讨论】:
【参考方案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>
【讨论】:
以上是关于对象数组的Angular2材质自动完成自定义过滤器的主要内容,如果未能解决你的问题,请参考以下文章