gpt4 book ai didi

angular - 使用 *ngFor 遍历数组并使用 *ngIf 从数组中选择要列出的元素

转载 作者:太空狗 更新时间:2023-10-29 17:30:29 27 4
gpt4 key购买 nike

我正在尝试使用 *ngFor循环遍历对象数组。我意识到我不能使用 *ngFor和一个 *ngIf在同一个元素上,它会返回一个错误。相反,我试着坚持我的 *ngIf关于列表项的内容。但是现在,我得到了一堆空列表项,它们正在创建并显示在我的 View 页面上。

我不想贴*ngFor在我的 <ul>元素,因为它会创建一堆 <ul>每个元素中有一个列表项。

我希望你们中的一个人能有另一种方法来实现它。

// 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>只需返回一定高度的空白空间即可。

此外,如果需要其他信息,请告诉我。

最佳答案

*ngFor 和 *ngIf(带星号)都是 structural directives他们生成<template>标签:

Structural directives, like ngIf, do their magic by using the HTML 5 template tag.

您可以使用以下语法获得所需的功能:

<ul>
<template ngFor #contact [ngForOf]="contacts">
<li *ngIf="checkList(contact) == true" >
<contact-detail [contact]="contact"></contact-detail>
</li>
</template>
</ul>

示例:http://plnkr.co/edit/JeDbVi4pXrzJ5SRIonjH?p=preview

关于angular - 使用 *ngFor 遍历数组并使用 *ngIf 从数组中选择要列出的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35786054/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com