Angular 12下Angular Material下拉框自动完成搜索功能失效
代码存在的问题
filteredOptions是Observable类型的流数据,模板中直接用*ngFor遍历无法解析,需要搭配async管道订阅流才能拿到实时过滤后的数组- 组件内直接调用
this.icons.valueChanges会抛出未定义错误,你没有声明icons对应的getter,需要从表单组实例中获取对应表单控件 _filter方法过滤逻辑错误:menuIconDropdown的每一项是包含value、text属性的对象,直接对option调用toLowerCase()会报错,需要先取对应字段值再做匹配mat-option的value绑定用插值写法会丢失类型,建议使用Angular标准输入绑定语法
修正后代码
HTML
<form [formGroup]="form" autocomplete="off"> ----other form fields--- <mat-form-field appearance="outline"> <mat-label class="label-padding">Menu Icon</mat-label> <input type="text" placeholder="Search Icon" formControlName="icons" matInput [matAutocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete"> <mat-option value="">Search icon</mat-option> <mat-option [value]="each.value" *ngFor="let each of filteredOptions | async" (click)="onSelFunc(each.value)"> <mat-icon>{{each.value}}</mat-icon> {{each.text}} </mat-option> </mat-autocomplete> </mat-form-field> </form>
COMPONENT
// 顶部引入Observable import { Observable } from 'rxjs'; // 修正类型定义 filteredOptions: Observable<any[]>; // 可选:定义icons的getter简化后续调用 get icons() { return this.form.get('icons'); } ngOnInit() { this.form = this.fb.group({ //others, icons: ['', Validators.compose([Validators.required])] }) this.menuIconDropdown = this.iconListModel.iconList; // 未定义上面的getter时,替换为this.form.get('icons').valueChanges this.filteredOptions = this.icons.valueChanges .pipe( startWith(''), map(value => this._filter(value)) ); } private _filter(value: string): any[] { const filterValue = value.toLowerCase(); // 可根据实际过滤需求,替换为匹配option.value return this.menuIconDropdown.filter((option: any) => option.text.toLowerCase().includes(filterValue)); } onSelFunc(option: any) { console.log(option); }
内容的提问来源于stack exchange,提问作者XenDex
相关产品推荐
相关产品推荐

