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>
                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>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With