Angular2 ngFor - skip if no value

Add a *ngIf on the repeating element and check with a falsy conditional on the length property like so:

<ul>
    <template ngFor let-item [ngForOf]="data.items">
        <li class="item" *ngIf="item?.description?.length">
            <div>{{item.title}}</div>
            <div>{{item.description}}</div>
        </li>
    </template>
</ul>

You can't access the item variable from the *ngFor in the *ngIf on the same element, that's why you need to add a template tag encapsulating the li.


Working Plunker for example usage


display only items that have a description?

Short solution

<ul *ngFor="let item of data.items">
    <li class="item" *ngIf="item.description">
        <div>{{item.title}}</div>
        <div>{{item.description}}</div>
    </li>
</ul>

OR use ng-container instead of template to keep the code clearer.

<ul>
    <ng-container *ngFor="let item of data.items">
        <li class="item" *ngIf="item.description">
            <div>{{item.title}}</div>
            <div>{{item.description}}</div>
        </li>
    </ng-container>
</ul>

Tags:

Angular