通过 Angular 中的 *ngIf 循环过滤给出错误

Filtering on a loop by *ngIf in Angular giving error

我试图通过循环实现的列表中的 *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"}
  ];

错误:

请帮助在上面的示例中根据年龄 < 30 过滤掉 li 行项目。谢谢。

这个错误已经很清楚了。使用 ng-container 作为其中之一。这是一个特殊的标签,不会在模板中呈现,但允许您在其上放置结构指令(如 ngIfngFor)。

<ul>
  <ng-container *ngFor="let x of students">
    <li *ngIf="x.age < 30">
      {{x.name}},{{x.age}}
    </li>
  </ng-container>
</ul>

但是,建议过滤掉代码中的元素而不是模板中的元素。使用 Array#filter 方法并将谓词指定为参数。这使代码更具可读性、可测试性、性能并且具有更好的关注点分离。