lah*_*han -2 autocomplete numeric angular-material angular mat-autocomplete
假设对象数组,
books = [{id:1, name: 'book1'}, {id:2, name: 'book2'}];
Run Code Online (Sandbox Code Playgroud)
在这里可以看到数组中每个元素的id都是一个数字。当对象数组为给定格式时,Angular 自动完成组件不起作用。任何解决方法?如何使用书的ID自动完成?
是的,您可以,您只需id在过滤之前将其转换为字符串。
我对示例进行了两项更改以使其正常工作,以便您可以按id.
首先在ngOnInit我确保使用对象的id属性Book传递给_filter函数。
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith<string | Book>(''),
map(value => typeof value === 'string' ? value : value.id),
map(id => id ? this._filter(id) : this.options.slice())
);
}
Run Code Online (Sandbox Code Playgroud)
而在_filter函数本身中,只需将 转换id为字符串。
private _filter(id: number | string): Book[] {
const filterValue = String(id);
return this.options.filter(option => String(option.id).toLowerCase().indexOf(filterValue) === 0);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1261 次 |
| 最近记录: |