角度过滤管不起作用

时间:2018-02-20 12:32:11

标签: angular angular-pipe

我使用角度5和角度材质2,我试图过滤*ngFor中的元素列表,就像你在这里看到的那样:

<div class="book" *ngFor="let book of documents |
 docCategory: fitleredCategories | sortBy: sortvalue : asc">

现在第二个过滤器正在运行,但第一个过滤器没有。

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'docCategory'
})
export class DocCategoryPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    let filtered = [];
    if (!value) {
      return;
    }

    filtered = value.filter((doc) => args.includes(doc.categories[0]));

    if (args.length === 0) {
      return value;
    } else {
      return filtered;
    }
  }

}

这是一组复选框,点击后将值推入fitleredCategories数组:

library.component.html

<li class="category" *ngFor="let category of categories">
  <mat-checkbox value="{{category.name}}" (click)="toggleCatInArray(category.name)">{{category.name}}</mat-checkbox>
</li>

toggleCatInArray仅检查fitleredCategories上是否存在值以推送或删除它。

但由于某种原因管道无效。

library.component.ts

public fitleredCategories: any = [];

  public toggleCatInArray(category): void {
    this.toggleInArray(category, this.fitleredCategories);
  }

我在控制台上没有收到任何错误或其他错误,它只是没有过滤*ngFor

2 个答案:

答案 0 :(得分:1)

问题是由两个原因造成的:

DocCategoryPipe执行不良:

@Pipe({
  name: 'docCategory'
})
export class DocCategoryPipe implements PipeTransform {

  transform(value: any[], categories: string[]): any[] {
    if (!value || !categories) {
      return [];
    }

    return value.filter((doc) => args.includes(doc.categories[0]));
  }
}

filteredCategories数组的突变:

为了在模板中重新运行管道,需要将新值/对象引用作为参数传递。当您改变其中一个参数时,Angular不会重新评估纯管道。

要解决此问题,请按以下方式重构代码:

 <li class="category" *ngFor="let category of categories">
  <mat-checkbox [value]="category.name" (change)="toggleCategory($event)">{{category.name}}</mat-checkbox>
</li>

import {MatCheckboxChange} from '@angular/material';

filteredCategories: string[] = [];
toggleCategory(event: MatCheckboxChange){
  const category = event.source.value;
  if(event.checked){
     this.filteredCategories= [...this.filteredCategories, category];
  }else{
     const matchIndex = this.filteredCategories.indexOf(category);
     this.filteredCategories= this.fitleredCategories.splice(matchIndex,1).
  }
}

正如您现在每次添加/删除类别时使用新对象引用设置filteredCategories时,angular将重新评估模板中的管道。

答案 1 :(得分:-2)

我认为你需要结合像

这样的管道
<div class="book" *ngFor="let book of (documents | docCategory: fitleredCategories) | sortBy: sortvalue : asc">

方法filter没有过滤当前数组。它返回一个新的数组。试试这段代码:

... 
return value.filter((document) => ...)
相关问题