使用* ngFor遍历数组,使用* ngIf选择数组中要列出的元素
我正在尝试使用*ngFor
遍历对象数组.我意识到我不能在同一元素上使用*ngFor
和*ngIf
,它将返回一个错误.相反,我尝试将*ngIf
粘贴在列表项的内容上.但是现在,我得到了一堆空列表项,它们正在创建并显示在我的视图页面上.
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.
我不想将*ngFor
粘贴在我的<ul>
元素上,因为这样会创建一堆<ul>
元素,每个元素中都包含一个列表项.
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>
和...
// ContactDetailComponent
<img />
<span>{{contact.name}}</span>
<span>{{contact.email}}</span>
发生了什么事
<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>
我正在使用Material Design Lite,因此所有这些元素都将具有一些CSS属性.空的<li>
只是返回一定高度的空白区域.
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.
Both *ngFor and *ngIf (with asterisk) are structural directives and they generate <template>
tag:
ngIf之类的结构指令通过使用HTML 5模板标记来发挥作用.
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>