0%

ng-template

顾名思义,ng-template是一个模板元素,通常与结构化指令ng-if, ng-for, ng-switch及模板变量配合使用.

ng-template配合ng-if

1
2
3
<ng-template [ngIf]="true">
<div>Hello, world!</div>
</ng-template>

在实际编程中,我们一般不用上面的写法,而是采用指令的简写形式,也就是用*ngIf代替[ngIf]

1
<div *ngIf="true">Hello, world!</div>

这段代码编译后的结果和第一段代码是相同的。关于指令的简写形式,请参考这篇。注意:在ng-template上使用指令的简写形式是无效的,必须使用属性绑定的方式,下面的代码无法正常工作。

1
2
3
<ng-template *ngIf="true">
<div>Hello, world!</div>
</ng-template>

作为elseBlock使用

假设有如下需求,当conditiontrue时,显示Hello, world!,否则显示Goodbye, world!, 该如何实现呢?
我们可以在ngIf指令后面添加else关键字,然后在else后面添加一个模板引用变量,然后定义一个ng-template并用该模版变量标识之,如下所示:

1
2
<div *ngIf="condition else otherTemplate">Hello, world!</div>
<ng-template #otherTemplate>Goodbye, world!</ng-template>

如果你使用的是Angular17及以上版本,那么你可以使用built-in control flow语法。

1
2
3
4
5
@if(condition) {
<div>Hello, world!</div>
} @else {
<div>Goodbye, world!</div>
}

If-then-else

如果两个分支对应的模板都很大,那么可以采用这种方式,使结构更清晰,代码更易读。

1
2
3
<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>Content to render when condition is true.</ng-template>
<ng-template #elseBlock>Content to render when condition is false.</ng-template>

同样的,如果你使用的是Angular17及以上版本,那么你可以使用built-in control flow语法。

1
2
3
4
5
@if(condition) {
<div>Hello, world!</div>
} @else {
<div>Goodbye, world!</div>
}

看到了吗,built-in control flow语法的可读性更强,更符合人类的思维方式。

References:

  1. Angular ng-template
  2. ng-container - https://zdd.github.io/2024/07/09/angular-ng-container/

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server

Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment