使用* ngFor遍历数组,使用* ngIf选择数组中要列出的元素 [英] Using *ngFor to loop through an array and *ngIf to select which elements from the array to list

查看:207
本文介绍了使用* 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.

推荐答案

* ngFor和* ngIf(带星号)均为

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>

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

这篇关于使用* ngFor遍历数组,使用* ngIf选择数组中要列出的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆