0%

angular-ngswitch

Introduction

ngSwitch is a structural directive in Angular, it is used to conditionally render a template based on the value of an expression.

Use ngSwitch with enum.

注意:我发现下面每个*ngSwitchCase分支都只包含一个<p>元素,所以我们可以将ng-container拿掉,直接把*ngSwitchCase放在<p>标签上。
但是如果case分支中有多个元素,那么就需要用ng-container包裹起来。

default分支用*ngSwitchDefault来标记。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!--app.component.html-->
<div class="account-feature-container" >
<ng-container [ngSwitch]="accountStatus">
<ng-container *ngSwitchCase="AccountStatus.CLOSED">
<p>This is a closed account</p>
</ng-container>
<ng-container *ngSwitchCase="AccountStatus.AUTHORIZED">
<p>This is an authorized account</p>
</ng-container>
<ng-container *ngSwitchCase="AccountStatus.NORMAL">
<p>This is an normal account</p>
</ng-container>
<p *ngSwitchDefault>This is the default branch</p>
</ng-container>
</div>

在Component中定义一个枚举类型,注意AccountStatus = AccountStatus;这一行是必须的,否则编译报错。

1
2
3
4
5
6
7
8
9
10
11
12
// app.component.ts
@Component({
selector: 'app-ng-switch',
templateUrl: './ng-switch.component.html',
styleUrls: ['./ng-switch.component.less']
})
export class NgSwitchComponent implements OnInit {
AccountStatus = AccountStatus; // Make enum visible in component.ts file.
public accountStatus: AccountStatus = AccountStatus.AUTHORIZED;
constructor() {}
ngOnInit(): void {}
}

Use built-in structural directive @switch.

1
2
3
4
5
6
7
8
9
10
11
12
13
<div class="use_built-in_control_flow">
@switch (accountStatus) {
@case (AccountStatus.CLOSED) {
<p>This is a closed account</p>
} @case (AccountStatus.AUTHORIZED) {
<p>This is an authorized account</p>
} @case (AccountStatus.NORMAL) {
<p>This is an normal account</p>
} @default {
<p>This is the default branch</p>
}
}
</div>

Tips:

  1. Remember to add the @default branch at the end, if no case matched, and no @default is provided, nothing will be rendered.
  2. There is no fallthrough in the @switch directive, so you don’t need to add break or return in each @case branch.