具有Angular搜索功能的Mat-select-filter实现器

问题描述 投票:0回答:1

我想在mat-select-filter模块中实现mat-select。我添加了一个搜索图标,用于根据输入的字符搜索下拉列表中的项目。我已经引用了这个mat-select-filterstackblitz,但是我没有得到filter字段。下面是我使用的代码

search-filter.component.html

 <mat-form-field class="input-permissions">
    <mat-select
      placeholder="Permissions"
      multiple
      [formControl]="permissionsControl"
    >
      <mat-select-filter
        [array]="permissions"
        (filteredreturn)="filteredList=$event"
      ></mat-select-filter>
      <mat-option
        *ngFor="let permission of permissions"
        [value]="permission.value"
      >
        {{ permission.value}}
      </mat-option>
    </mat-select>
  </mat-form-field>

mat-select-filter.component.ts

    export class MatSelectFilterComponent{
       permissions: {{id: 0, value: fruit},{id: 1, value: vegetable} };
       public filteredList = this.permissions.slice();
    }

任何帮助将不胜感激。

angular angular-material
1个回答
1
投票
  1. permissions必须是Array,而不是object

    public permissions = [{id: 0, value: 'fruit' },{id: 1, value: 'vegetable'} ];
    public filteredList = this.permissions.slice();
    
  2. 您需要在displayMember上指定mat-select-filter,并且filteredreturn应该为filteredReturn

    <mat-select-filter [array]="permissions" (filteredReturn)="filteredList=$event" [displayMember]="'value'">
    </mat-select-filter>
    
  3. 如果使用多重选择,则需要自己隐藏未过滤的结果。否则,您可以仅遍历filteredList,但在这种情况下,过滤时会删除旧的选择。而是遍历permissions,然后隐藏那些不应该显示的内容。

    <mat-option *ngFor="let permission of permissions" [value]="permission"
        [class.hide]="!isFiltered(permission)">
        {{permission.value}}
    </mat-option>
    

    和用于检查过滤元素的功能

    public isFiltered(permission) {
      return this.filteredList.find(item => item.id === permission.id)
    }
    

    和隐藏的CSS

    .mat-option.hide {
      display: none;
    }
    
  4. 没有默认支持将某些图标添加到过滤器-至少我没有找到一个图标。不过,您可以使用CSS解决此问题。

    将其添加到index.html以确保正确加载字体:

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    

    将以下内容添加到您的CSS。它添加一个::after元素,其中包含搜索图标作为字体。请注意,将width元素的input减小图标所需的空间(此处为20px width5px padding-left),以确保将其彼此相邻放置。

    .mat-filter-input {
      width: calc(100% - 25px) !important;
    }
    
    .mat-filter::after {
      content: "\e8b6";
      font-family: material icons;
      vertical-align: bottom;
      font-size: 20px;
      padding-left: 5px;
    }
    

    我需要在组件内设置encapsulation: ViewEncapsulation.None,因为否则样式将使用错误的选择器。我不确定这是否是stackblitz问题。不尝试它。如果可行,您也可以从!important元素的width中删除input

这里是堆栈闪电解决方案的链接:https://stackblitz.com/edit/mat-select-filter-zuy7ev

© www.soinside.com 2019 - 2024. All rights reserved.