Apply a condition using ngFor and ngIf in angular 2 [duplicate]

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.

Leave a Comment