我正在运行angular6应用程序,我想实现自动完成功能,其中数据是要拖放的对象,在键入时必须对其进行过滤。
**template.html**
<mat-form-field >
<input matInput [matAutocomplete]="auto" [formControl]="customerFilterControl">
<mat-autocomplete #auto="matAutocomplete" [displayWith] = "displayFn">
<mat-option *ngFor="let option of (filteredOptions | async)" [value] ="option">
{{option.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
打字稿
import { Observable } from 'rxjs';
import { FormControl } from '@angular/forms';
import { map, startWith } from 'rxjs/operators';
export class Component1 implements OnInit {
objectOptions = [
{ name:'Angular' },
{ name:'Angular Material' },
{ name:'React' },
{ name: 'vue' }
];
customerFilterControl = new FormControl();
ngOnInit() {
this.filteredOptions = this.customerFilterControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
);
}
_filter(value:string):string[] {
const filterValue = value.toLowerCase();
return this.objectOptions.filter(option => option.toLowerCase().includes(filterValue)); // how do I filter values here
}
displayFn(subject) {
return subject ? subject.name : undefined;
}
注意:我已经在app.module.ts中导入了以下模块MatSelectModule,MatAutocompleteModule,MatFormFieldModule,MatInputModule
当我尝试通过名称属性过滤对象时,它给我错误
如果您提供了所得到的错误,将会有所帮助。
但是,说到我可以看到错误的地方,它就是这一行:
this.objectOptions.filter(option => option.toLowerCase().includes(filterValue))
这option
是一个对象,您正在尝试调用toLowerCase()
,我想您尝试做的是:
this.objectOptions.filter(option => option.name.toLowerCase().includes(filterValue))
编辑刚刚看到了另一个错误。
_filter(value:string):string[]
当您实际上返回具有name属性的对象数组时,您将函数声明为返回字符串数组。如果您删除了返回类型并允许打字稿进行推断,那么您应该不再出错。或将其更改为:
_filter(value:string): {name: string}[]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句