Apply condition using ngFor and ngIf in angular 2

Hey. There I tried, with some success, to filter the array using ngIF and ngFor.

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


This code only shows buttons with a name in it for data with type = 1, but also creates empty buttons for every data record that doesn't have type = 1, I can't figure out how to get rid of the empty buttons. Any help is greatly appreciated.


source to share

3 answers

I would flip yours button

and div


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


Only buttons for valid items are created this way.

You can also use a function in your component:

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


If your component has a function:

    return this.items.filter(x => == type);




You can create your own channel. This is the best solution.

    name: 'somepipe',
export class SomePipe {

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



and use it in html like this:

<button *ngFor="let item of items | somepipe"> <div> {{}} </div> </button>




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

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


where this.items

is your array of elements above this function.

check it



All Articles