Lea
Lea

Reputation: 1285

Angular2 How to ngFor specific Data

I am having difficulty showing data with specifications.

For example, I have a list of available teachers, but I want to show only female teachers.

Consider the following data, where 'userInfo' has 10 user data within the array. I only want to show female teachers.

userInfo = [
    {gender: 'Male', Age: 25, name: John, teacherDetail : [...]},
    {gender: 'Female, Age: 26, name: Jessie, teacherDetail: [...]},
    ...
]

How can I achieve this? Should I use filter pipe?

Upvotes: 0

Views: 412

Answers (1)

Pengyy
Pengyy

Reputation: 38161

There are several ways to achieve it:

Option1: call function which filter data at component

<div *ngFor="let user of getUserInfo()">
  show female teacher only
</div>

getUserInfo() {
  return this.userInfo.filter(user => user.gender === 'Female');
}

Option2: use simple *ngIf to control what to show

<div *ngFor="let user of userInfo">
  <div *ngIf="user.gender === 'Female'">
    show female teacher only
  </div>
</div>

Option3: use custom filter which filter data at Pipe(transform part is the same as Option1)

<div *ngFor="let user of userInfo | filterOnlyFemale">
  show female teacher only
</div>

transform(input: any) {
  return this.userInfo.filter(user => user.gender === 'Female');
}

Upvotes: 4

Related Questions