【发布时间】:2019-03-05 04:17:23
【问题描述】:
我试图通过 *ngIf 在通过循环实现的列表中过滤掉一些项目,但它给出了错误。请帮忙。
abc.component.html
<ul>
<li *ngFor="let x of students" *ngIf="x.age < 30">{{x.name}},{{x.age}}</li>
</ul>
abc.component.ts
students = [
{name: "Jack", age: 29, gender:"male", country: "USA"},
{name: "Ronald", age: 33, gender: "male", country: "UK"},
{name: "Lisa", age: 19, gender: "female", country: "UK"},
{name: "Donald", age: 43, gender: "male", country: "Austrailia"},
{name: "Simera", age: 23, gender: "female", country: "Italy"}
];
错误:
请帮助在上面的示例中根据年龄
【问题讨论】:
-
你不能在同一个元素上有
ngIf和ngFor。使用students.filter(s => s.age < 30)过滤 TS 代码中的数组 -
@Matt - 不,不是。那个管子太烂了。
-
为此使用管道确实是一个糟糕的决定。最好的解决方案是简单地在代码中而不是在模板中进行过滤,但是学习如何摆脱上述错误也很重要。
-
@user184994:如果这是一个答案,我会接受的。 (而不是评论)。 -- 成功了。
标签: javascript angular angular-directive ngfor angular-ng-if