Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

274
Views
Apply a condition using ngFor and ngIf in angular 2

Hi There I have been trying to filter an array with some success using ngIF and ngFor.

<button *ngFor="let item of items"> <div *ngIf="(item.data.type == 1)"> {{item.data.name}} </div> </button>

This code does only show buttons with name in it for data that has type=1 but it also create empty buttons for each data entry that doesn't have type=1, I can't figure out how to get rid of empty buttons. Any help is much appreciated.

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

I would flip-flop your button and div:

<div *ngFor="let item of items">
    <button *ngIf="(item.data.type == 1)">{{item.data.name}}</button>
</div>

This way only buttons get created for valid items.

If <div>'s aren't desirable use <ng-container> instead.

Though not advisable due to performance reasons, you can also use a function in your component:

<button *ngFor="let item of filterItemsOfType('1')">{{item.data.name}}</button>

Where your component has a function:

filterItemsOfType(type){
    return this.items.filter(x => x.data.type == type);
}

While this works, it is not recommended and should be avoided where possible.

about 4 years ago · Santiago Trujillo Report

0

You can create your own pipe. That is better solution.

@Pipe({
    name: 'somepipe',
})
export class SomePipe {

    transform(objects: any[]): any[] {
        if(objects) {
            return objects.filter(object => {
                return object.data.type === 1;
            });
        }
    }

}

and use it in html in this way:

<button *ngFor="let item of items | somepipe"> <div> {{item.data.name}} </div> </button>
about 4 years ago · Santiago Trujillo Report

0

<button *ngFor="let item of getItems()">...</button>

getItems() {
  return this.items.filter((item) => item.data.type === 1);
}

where this.items is your array of items somewhere above this function.

Check this out

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!