gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:17:06 31 4
gpt4 key购买 nike

我有以下组件:

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>

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

最佳答案

使用过滤函数过滤数据:

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

在模板中:

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

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

::链接已编辑::

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

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

关于angular - 在 ngFor 中按值过滤项目而不编写管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47406804/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com