在ngFor内部按值过滤项目,而无需编写管道 [英] Filtering items by value inside ngFor without writing Pipes

查看:135
本文介绍了在ngFor内部按值过滤项目,而无需编写管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下组件:

class MyComponent {
  public mode = 'v';
  readonly modes = ['v', 'a', 'd'];
  ....
}

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

Now I want to use an ngFor to display buttons for all modes in modes except the current mode stored in mode. I have the following code:

<button *ngFor="let othermode of modes">
  {{ othermode }}
</button>

我总是希望显示两个按钮,其中包含其余2种模式.我试过了:

I always want two buttons to be displayed, containing the remaining 2 modes. I tried this:

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

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

but it isn't working. All questions I saw required to write a custom pipe for this feature, but isn't there any simple way to filter an array of strings, using just the values ?

推荐答案

您可以使用:

<ng-container *ngFor="let othermode of modes">
  <button *ngIf="othermode!=mode">
    {{ othermode }}
  </button>
</ng-container>

这篇关于在ngFor内部按值过滤项目,而无需编写管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆