加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 使用* ngFor循环遍历数组,使用* ngIf选择要列出的数

发布时间:2020-12-17 06:54:41 所属栏目:安全 来源:网络整理
导读:我正在尝试使用* ngFor循环遍历一个对象数组.我意识到我不能在同一元素上使用* ngFor和* ngIf,它会返回错误.相反,我试图将我的* ngIf粘贴在列表项的内容上.但是现在,我得到了一堆空的列表项,它们正在我的视图页面上创建和显示. 我不想在我的 ul上坚持使用* n
我正在尝试使用* ngFor循环遍历一个对象数组.我意识到我不能在同一元素上使用* ngFor和* ngIf,它会返回错误.相反,我试图将我的* ngIf粘贴在列表项的内容上.但是现在,我得到了一堆空的列表项,它们正在我的视图页面上创建和显示.

我不想在我的< ul>上坚持使用* ngFor因为那时它会创建一堆< 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读