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

Filtering items by value inside ngFor without writing Pipes

我有以下组件:

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

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

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

我一直想要显示两个按钮,包含剩余的2种模式。我试过这个:

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

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

使用 ng-template 和 ngIf,如果你想用条件迭代数组。 下面是示例代码。你可以找到 working version here

<ng-template ngFor let-othermode [ngForOf]="modes">
<button *ngIf="othermode!=mode">
  {{ othermode }}
</button>
</ng-template>

您可以使用:

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

使用过滤函数过滤数据:

filterFunction(allButtons): any[] {  
    return allButtons.filter(buttom => buttom !== this.mode);
}

并在模板中:

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

要过滤对象,我建议使用现有组件。查看此线程:

::LINK 已编辑::

https://stackblitz.com/edit/angular-ivy-wngx-filter

https://stackblitz.com/edit/article-demo