首页 > 解决方案 > 下拉列表中的自动完成搜索不起作用(Angular 12)

问题描述

我尝试了几种方法来解决 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"(click)="onSelFunc(each.value)">
                        <mat-icon>{{each.value}}</mat-icon> {{each.text}}
                      </mat-option>
                    </mat-autocomplete>
        </mat-form-field>
     </form>

零件:

filteredOptions: any
ngOnInit() {
    this.form = this.fb.group({
      //others,
      icons: ['', Validators.compose([Validators.required])]
    })
    this.menuIconDropdown = this.iconListModel.iconList;
    this.filteredOptions = this.icons.valueChanges
      .pipe(
        startWith(''),
        map(value => this._filter(value))
      );
      console.log(this.filteredOptions );
  }
private _filter(value: string): string[] {
    console.log(value);
    const filterValue = value.toLowerCase();
    return this.menuIconDropdown.filter((option: any) => option.toLowerCase().includes(filterValue));
  }
  onSelFunc(option: any) {
    console.log(option);
  }

下拉列表显示正确,但搜索和自动完成功能根本不起作用。

谁能告诉我我在这里犯了什么错误?

标签: angularangular-materialautocompletedropdownangular12

解决方案


过滤器函数的返回类型是string[]并且你menuIconDropdown的是键值列表,所以你的过滤器函数应该是这样的:

private _filter(value: string): any[] {
    console.log(value);
    const filterValue = value.toLowerCase();
    return this.menuIconDropdown.filter((option: any) => option.text.toLowerCase().includes(filterValue));
  }

推荐阅读