【问题标题】:Angular material Autocomplete filter object with keyvalue pipe带有键值管道的角度材料自动完成过滤器对象
【发布时间】:2020-09-21 23:16:14
【问题描述】:

我有个小问题,我有这个:

foo = {
   parent1:[{
              data: "John",
           },
           {
              data: "Adam",
           },
           {
              data: "Eva",
           }],
   parent2:[{
              data: "Ricky",
           }]
}

还有我的自动完成功能:

<input type="text" matInput [formControl]="query" [matAutocomplete]="autoGroup"/>
<mat-autocomplete #autoGroup="matAutocomplete">
  <mat-optgroup *ngFor="let parents of foo | keyvalue" [label]="parents.key">
    <mat-option *ngFor="let data of parents.value"  [value]="data.data">
      {{ data.data }}
    </mat-option>
  </mat-optgroup>
</mat-autocomplete>

我想给它设置一个过滤器——我只想按“数据”过滤,例如。如果我输入“John” - 它只会保留 John 和 optgroup “parent1” 我已经创建了演示:

https://stackblitz.com/edit/angular-syzdzg-ytejbp?file=src%2Fapp%2Fautocomplete-filter-example.html

提前致谢!

【问题讨论】:

    标签: angular autocomplete angular-material


    【解决方案1】:

    我不建议您使用KeyValuePipe 管道,因为它不纯,这意味着它会被调用并将您的对象转换为每个更改检测周期的新数组。请参阅文档的 Pure and impure pipes 部分和此 SO question

    在任何情况下,将对象转换为数组并对其进行过滤更容易。您可以在angular material docs 中找到filter autocomplete 示例。在您的情况下,它看起来像:

    ...
    @Component(...)
    export class AutocompleteFilterExample {
      ...
    
      readonly filteredFoo$ = this.query.valueChanges.pipe(
        map((query = '') => {
          const lowerCaseQuery = query.toLocaleLowerCase().trim();
          return Object.entries(this.foo)
            .map(([parentId, items]) => ([
              parentId,
              items.filter(item => {
                const lowerCaseData = item.data.toLocaleLowerCase();
                return lowerCaseData.includes(lowerCaseQuery);
              })
            ]))
            .filter(([prentId, items]) => items.length);
        })
      );
    }
    
    <input type="text" matInput [formControl]="query" [matAutocomplete]="autoGroup"/>
    <mat-autocomplete #autoGroup="matAutocomplete">
      <mat-optgroup *ngFor="let parents of filteredFoo$ | async" [label]="parents[0]">
        <mat-option *ngFor="let data of parents[1]"  [value]="data.data">
          {{ data.data }}
        </mat-option>
      </mat-optgroup>
    </mat-autocomplete>
    

    StackBlitz

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      相关资源
      最近更新 更多