新新新手阅读 Angular 文件 - ngFor(2) - Day20

本文内容

将 ngIf 和 ngFor 彼此之间怎麽搭配使用的方法记录下来。

structural directive

在 Angular 中的 ngIf 和 ngFor 都是叫做 structural directive。
官方文件介绍 ngForOf 这个 API 的时候,有特别写下以下这段话,
https://ithelp.ithome.com.tw/upload/images/20210920/20140093AqinjqHKxt.png

它有特别声明,在使用 shorhand syntax (即: *ngIf, *ngFor 这种写法) 的时候,在一个元素上只能使用一个 structural directive。

ngFor 和 ngIf 混用 - ng-container

那如果,透过 ngFor 遍历某个阵列,而我想要用 ngIf 有条件的渲染其中的某些元素的话,要怎麽达到呢?!!
这个时候,我们就可以使用 ng-container 来达到这种效果喔
[View]

<ul>
  <ng-container *ngFor="let item of itemInfo">
    <li *ngIf="item.visible">
      {{ item.name }}
    </li>
  </ng-container>
</ul>

[TypeScript]

export class AppComponent {
  itemInfo = [
    { name: 'cup', visible: true },
    { name: 'coffee', visible: true },
    { name: 'tea', visible: true },
    { name: 'chocolate', visible: false },
  ];
}

有看到上面的范例,我们将 ngFor 的内容放到 ng-container 元素上,接着,才在里面放入 ngIf 来判断是否该元素的属性有符合条件,若有才会为它渲染出属於它的 li 元素。
另外,ng-container 是不会产生出额外的 DOM 在你的网页上喔,所以,不用担心会不会又需要额外产出不必要的 DOM 出来。

ngFor 和 ngIf 混用 - ng-template

除了用 ng-container 可以达成 ngFor 和 ngIf 的混用,我们也可以利用 ng-template 来达成喔,止步过写法上就比较不一样了。会造成写法上的不一样是因为 ng-template 是没有办法直接写入 shorthand syntax 的内容,即像是: *ngFor, *ngIf 这种简写的 syntax 是没有办法直接加在 ng-template 上,我们必须把整个内容都写上去才行。
那麽就来改写一下上面的范例吧
[View]

<ul>
  <ng-template ngFor let-item [ngForOf]="itemInfo">
    <li *ngIf="item.visible">
      {{ item.name }}
    </li>
  </ng-template>
</ul>

[TypeScript]

export class AppComponent {
  itemInfo = [
    { name: 'cup', visible: true },
    { name: 'coffee', visible: true },
    { name: 'tea', visible: true },
    { name: 'chocolate', visible: false },
  ];
}

用 ng-template 的写法是不是有点冗呢 XDDD,所以,你如果不想写那麽多的内容的话,就建议直接使用 ng-container 的写法罗~~

Summary

这边做个总结

  1. 在 Angular 中有规定 一个元素上只能加入一个 structural directive 的内容。
  2. 搭配 ng-container 或 ng-template ,来达到 ngFor 和 ngIf 混用的效果。

Reference

  1. https://stackoverflow.com/questions/34657821/ngif-and-ngfor-on-same-element-causing-error
  2. https://angular.io/api/common/NgForOf

<<:  抽象类别和介面 (2)

>>:  Day18-pytorch(1)认识tensor

[CSS] Flex/Grid Layout Modules, part 10

来到了 30 天的三分之一,然後我才刚讲完网格容器而已,但是,剩下的东西也不多了,好像要写满 30 ...

人脸辨识-day20 资料预处理--1

在做模型训练时,要先将训练资料做一些事前的处理,为以下这几类:资料平衡、异常点处理、缺失值处理、特徵...

[Day 22] 资料产品在需求访谈阶段的五个大坑

最後几天来回顾一下在过去开发资料产品时常见的坑与应对方式,不管是专案还是产品,首先当然要面对的难题就...

Day33:HTML(30) HTML响应式网页设计

HTML响应式网页设计 响应式网页设计(英语:Responsive web design,通常缩写为...

MySQL 群组函数之基本操作

最近要去当兵,所以在进去前多少学一下资料库。 SELECT COUNT( * ) FROM tabl...