Issue
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
Both *ngFor and *ngIf (with asterisk) are structural directives and they generate <template> tag:
Structural directives, like ngIf, do their magic by using the HTML 5 template tag.
You can get functionality you want with this syntax:
<ul>
<template ngFor #contact [ngForOf]="contacts">
<li *ngIf="checkList(contact) == true" >
<contact-detail [contact]="contact"></contact-detail>
</li>
</template>
</ul>
example: http://plnkr.co/edit/JeDbVi4pXrzJ5SRIonjH?p=preview
Answered By - Sasxa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.