首页 > 解决方案 > 如何在 Angular 中制作动态过滤器管道(组合标准)?

问题描述

我打算在这段代码中实现的是通过选择的过滤器打印卡片。例如:

类别是

类型:

地位:

因此,如果选择浪漫、惊悚、待定,它将仅显示这些卡片。

到目前为止,我实现的是它只显示一项。

这是我管道上的代码

 transform(Projects: Project[], criteriaValue: any, properties: string[]): any[] {
    if (!Projects) return [];
    if (!criteriaValue) return Projects;
    debugger;
    return Projects.filter(item => {
      var itemFound: Boolean;
      for (let i = 0; i < properties.length; i++) {
        if (item[properties[i]].toLowerCase().indexOf(criteriaValue.toLowerCase()) !== -1) {
          itemFound = true;
          break;
        }
      }
      return itemFound;
    });

  }

html:

 <div class="btn-row">
            <button mat-stroked-button aria-label="large icon" (click)="filterCriteria = 'Romance'"  > Romance</button>  
            <button mat-stroked-button aria-label="large icon"  (click)="filterCriteria = 'Thriller'" > Thriller</button> 
            <button mat-stroked-button aria-label="large icon"  (click)="filterCriteria = 'Fantasy'" > Fantasy</button> 
            <button mat-stroked-button aria-label="large icon"  (click)="filterCriteria = 'pending'" > pending</button> 
            <button mat-stroked-button aria-label="large icon"  (click)="filterCriteria = 'Hiatus'" > Hiatus</button> 
        </div>

<li *ngFor="let novel of (novelList | Searchfilter: searchValue | criteriafilter:filterCriteria:['Genre','Status']  )"> 

  <li>[[novel.title]]</li>

我不完全确定要在我的组件上放什么,所以它会做我打算做的事情。提前感谢您的帮助:D

编辑:

这是我到目前为止所做的,但在 .toString 上出现错误

管道:

 transform(Projects: Project[], criteriaValue: [], properties: []): any {
    criteriaValue.forEach((name, index) => {
      if (name) {
        Projects = Projects.filter((item) => {
          return (item[properties[index]]
            .toString()
            .toLowerCase()
            .indexOf(name.toString().toLowerCase()) !== -1)
        });
      }
    });
    return Projects;
  }

我将我的 html *ngFor 更改为:

<div  fxFlex= " (100/3) %" fxFlex.xs="100%" fxFlex.sm = 33% *ngFor="let project of (cardList | Searchfilter: searchValue | criteriafilter: [sectorCriteria, timeHorCriteria] : ['sectors','time_horizon']  )"> 

如您所见,我正在尝试将标准绘制到一个数组中,但我似乎做错了。

任何形式的帮助都将受到高度赞赏。

错误是

“从不”类型上不存在属性“toString”。

标签: angulartypescript

解决方案


我只需像这样添加 any[] 就可以了:

transform(Projects: Project[], criteriaValue: any[], properties: any[]): any {
        criteriaValue.forEach((name, index) => {
          if (name) {
            Projects = Projects.filter((item) => {
              return (item[properties[index]]
                .toString()
                .toLowerCase()
                .indexOf(name.toString().toLowerCase()) !== -1)
            });
          }
        });
        return Projects;
      }

推荐阅读