Fra*_*ank 3 autocomplete angular
我正在努力了解在使用对象时如何使用 Angular Material Autocomplete。我基本上遵循了 Angular Docs,只是用一个选项对象替换了选项数组,但我不确定如何让它工作。介意看看这里吗?如果它在其他地方有很多答案,我将删除该问题。
这是我的 html 和 ts 组件。所有的进口和一切都是正确的,所以我没有展示任何这些。
<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()));
}
Run Code Online (Sandbox Code Playgroud)
你快到了,你只需要将数组映射到对象的内部属性。这是必要的,因为过滤器函数的返回值是一个字符串数组。
filter(val: string): string[] {
return this.options.map(x => x.color).filter(option =>
option.toLowerCase().includes(val.toLowerCase()));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6174 次 |
| 最近记录: |