Search code examples
htmlangulartypescriptngfortypescript-types

How do I display only certain data types with ngFor in Angular?


I'm iterating over the array called "fruits", containing objects of type "FruitService" - a class I defined and want to display each element, but after deleting them (I realize this is weird-no db) they become of type "undefined" contaminating my array. I don't want these to display (they show up as blank) so I want to display only "FruitService" objects. How do I do that?

<ul>

<li *ngFor="let fruit of fruits">
{{ fruit.name }}  price: {{ fruit._price }}   qty: {{ fruit.qty }}

</ul>

Solution

  • This issue is better handled off in the controller. Ideally, there should be no undefined elements in the array when the corresponding element is removed. They should actually be removed from the array.

    That said, you could do a simple check in the template to see if the element is defined before rendering them

    <ul>
      <ng-container *ngFor="let fruit of fruits">
        <li *ngIf="fruit">
          {{ fruit.name }}  price: {{ fruit._price }}   qty: {{ fruit.qty }}
        </li>
      </ng-container>
    </ul>
    

    The ng-container tag would be commented out in the final DOM and won't generate additional elements.