gpt4 book ai didi

用于对象数组的 Angular2 Material 自动完成自定义过滤器

转载 作者:行者123 更新时间:2023-12-03 22:57:53 24 4
gpt4 key购买 nike

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"}
];

最佳答案

以下代码对我有用:

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 Material 自动完成自定义过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47770553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com