Search code examples
javascriptangularangular-directivengforangular-ng-if

Filtering on a loop by *ngIf in Angular giving error


I am trying to filter out some items by *ngIf on a list achieved by looping, but it is giving error. Kindly help.

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"}
  ];

Error:

enter image description here

Kindly, help in filtering out rows of li items based on age < 30 in the above example. Thank You.


Solution

  • The error pretty much spells it out for you. Use ng-container for one of them. It's a special tag which won't be rendered in the template, but allows you to place structural directives (like ngIf, ngFor) on it.

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

    It's however, advisable to filter out elements in the code rather than in the template. Use the Array#filter method and specify your predicate as the argument. This makes code more readable, testable, performant and has better separation of concerns.