在ngFor内按值过滤项目而不编写管道

Dan*_*ane 7 ngfor angular

我有以下组件:

class MyComponent {
  public mode = 'v';
  readonly modes = ['v', 'a', 'd'];
  ....
}
Run Code Online (Sandbox Code Playgroud)

现在我想用a ngFor来显示所有模式的按钮,modes除了存储的当前模式mode.我有以下代码:

<button *ngFor="let othermode of modes">
  {{ othermode }}
</button>
Run Code Online (Sandbox Code Playgroud)

我总是希望显示两个按钮,包含剩余的两个模式.我试过这个:

<button *ngFor="let othermode of modes.filter(elem => elem !== this.mode)">
  {{ othermode }}
</button>
Run Code Online (Sandbox Code Playgroud)

但它不起作用.我看到的所有问题都需要为此功能编写自定义管道,但是没有任何简单的方法来过滤字符串数组,只使用这些值?

小智 12

使用过滤功能过滤数据:

filterFunction(your_collection): any[] {  
    return your_collection.filter(i => i.field.value === filterKey);
}
Run Code Online (Sandbox Code Playgroud)

并在模板中:

*ngFor="let value of filterFunction(datasource)"
Run Code Online (Sandbox Code Playgroud)

或者使用存在的组件.看线程:

/sf/answers/3505023371/

  • 这是 Angular 开发人员向 v6+ 发展的建议方式。[无过滤器/orderBy 管道](https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe) 对他们来说,这个决定是由于生产部署中的缩小以及随之而来的重大性能问题使用非纯管道(每次更新都重新运行管道)。他们还评论说,他们更喜欢将逻辑从 html 驱动到打字稿中……所以我将以这种方式思考未来的任何开发,以帮助防止弃用! (3认同)

Viv*_*shi 11

您可以使用 :

<ng-container *ngFor="let othermode of modes">
  <button *ngIf="othermode!=mode">
    {{ othermode }}
  </button>
</ng-container>
Run Code Online (Sandbox Code Playgroud)

  • 这不可能是正确的解决方案,因为当您不想显示列表时为什么需要迭代列表。最好先过滤列表。 (2认同)