Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 ngFor - skip if no value

Tags:

angular

I have this json object:

data = {

  "name": "somename",
  "items": [
    {
      "title": "Item 1",
      "description": "Some description for item1"
    },
    {
      "title": "Item 2",
      ""
    },
    {
      "title": "Item 3",
      "description": "Some description for item3"
    }
  ]
}

What would be the recommended way, with rc2, to *ngFor and display only items that have a description?

Html Template:

<li *ngFor="let item of data.items" class="item">
        <div>{{item.title}}</div>
        <div>{{item.description}}</div>
</li>
like image 861
Pat M Avatar asked Jun 28 '16 14:06

Pat M


2 Answers

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

like image 113
rinukkusu Avatar answered Nov 13 '22 15:11

rinukkusu


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>
like image 1
Reza Taba Avatar answered Nov 13 '22 13:11

Reza Taba