Angular ng-container 与 ng-template

接续昨天的范例。
今天要聊的是 ng-containerng-template

<ng-container *ngIf="(products$ | async)?.length > 0; else empty">
  <ng-container *ngFor="let item of (products$ | async)"> ...略 </ng-container>
</ng-container>
<ng-template #empty> No Data </ng-template>

上面程序码所要表达的是,若是资料大於 0 笔,页面上就会呈现列表,没有资料的时後在画面上显示 No Data


ng-container

ng-container 在 Angular 的 template 里,它不属於任何一个 tag,也不会被渲染出来。
而它通常都会被拿来处理一些逻辑的事情,如 *ngIf*ngFor

虽然 *ngIf*ngFor 这些也能写在 div 上,不过 div 它会被呈现出来,有时後会影响排版,这时後 ng-container 就是我们的好朋友惹!


ng-template

因为在 ng-container 有使用到 if/else,所以这时後就需要一个 ng-template 来做搭配,通常它不会直接显示出来,而是需要透过其他的指令,如ngIf 或是 TemplateRef 的搭配,当条件成立後,ng-template 里的内容才会被呈现


TemplateRef

.ts

export class TemplateComponent implements OnInit, AfterViewInit {
  @ViewChild('tpl') tplRef!: TemplateRef<any>;

  constructor(private viewContainerRef: ViewContainerRef) {}

  ngOnInit(): void {}

  ngAfterViewInit() {
    this.viewContainerRef.createEmbeddedView(this.tplRef);
  }
}

.html

<ng-template #tpl> Hello, Angular ! </ng-template>

ng-template 处理多重结构指令

来看一下昨天的 ngIf as 的 范例

<ng-container *ngIf="(products$ | async) as products;">
  <ng-container *ngIf="products.length > 0; else empty">
    <ng-container *ngFor="let item of products"> ...略 </ng-container>
  </ng-container>
</ng-container>
<ng-template #empty> No Data </ng-template>

光是 ng-container 就写了三层,那有没有办法再更简化一些呢!?
那我们可以使用 ng-template 这样处理

<ng-container *ngIf="(products$ | async) as products; else empty">
  <ng-template *ngIf="products.length > 0" ngFor let-item [ngForOf]="products">
    <div class="products">...略</div>
  </ng-template>
</ng-container>

後记

在 Angular 里有一些 xxxOutlet 的指令
如 ngTemplateOutletngComponentOutlet
接着 明天再来说说 ng-template 与 ngTemplateOutlet 这部份吧

参考资料

NgForOf
ViewContainerRef
Angular *ngIf variable with async pipe multiple conditions


<<:  Day11-TypeScript(TS)的类别(Class)

>>:  Day12 Vue Event Handing(v-on)

JavaScript基本功修练:Day28 - Fetch练习(GET和POST请求)

今天会承接昨天AJAX的课题,了解常用来处理AJAX的语法,Fetch,以及试试用fetch来实作G...

【C++】Binary Search

Binary Search 是一个搜寻演算法~ 它的时间复杂度只有O log(n)~ 但使用它之前要...

30天打造品牌特色电商网站 Day.9 RWD响应式设计介绍

哈罗~很快的已经来到了第九天,前面带给大家都是一些网页的基础,後面会针对各种主题有更深入的探讨喔,今...

[Day 27]-【STM32系列】UART/USART RX 资料接收篇(下)

昨日[Day 26]-【STM32系列】UART/USART TX 资料传送篇(上)我们体验了UAR...

[Android Studio 30天自我挑战] 变更Spinner字体及背景样式

Spinner选项的字体大小及背景都是可以更改的! 但Spinner的字体样式及背景无法像Textv...