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="(item.data.type == 1)"> {{item.data.name}} </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.

+3


source to share


3 answers


I would flip yours button

and div

:

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

      

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')">{{item.data.name}}</button>

      

If your component has a function:

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

      

+22


source


You can create your own channel. This is the best 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 like this:

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

      

+5


source


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

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

      

where this.items

is your array of elements above this function.

check it

0


source







All Articles