'Using *ngFor to loop through an array and *ngIf to select which elements from the array to list
I'm trying to use *ngFor to loop through an array of objects. I realized I couldn't use *ngFor and an *ngIf on the same element, it would return an error. Instead, I tried to stick my *ngIf on the contents of the list item. But now, I'm getting a bunch of empty list items and they're being created and displayed on my view page.
I don't want to stick the *ngFor on my <ul> element because then it will create a bunch of <ul> elements with a single list item within each.
I'm hoping one of you will have another method of implementing this.
// AppComponent
// contacts: Contact[]; // An array of `Contact` Objects
<ul>
<li *ngFor="#contact of contacts">
<contact-detail *ngIf="checkList(contact) == true" [contact]="contact"></contact-detail>
</li>
</ul>
and...
// ContactDetailComponent
<img />
<span>{{contact.name}}</span>
<span>{{contact.email}}</span>
What is happening:
<ul>
<li>
<!--template bindings={}--> // ngIf conditional returned true
<img />
<span>Name1</span>
<span>Email1</span>
</li>
<li>
<!--template bindings={}--> // ngIf conditional returned false
</li>
<li>
<!--template bindings={}--> // false
</li>
<li>
<!--template bindings={}--> // true
<img />
<span>Name1</span>
<span>Email1</span>
</li>
</ul>
I'm using Material Design Lite, so all these elements will have some css properties. Empty <li> just return an empty space of a certain height.
Also, if other information is needed, please let me know.
Solution 1:[1]
Sasxa's answer didn't work for me at 2022. You can use ng-template instead of template to get the same result.
<ul>
<ng-template ngFor let-item [ngForOf]="calcService.myDataArray">
<li *ngIf="item.esTarifa === true">
{{item.id}}
</li>
</ng-template>
</ul>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
