Skip to content

控制流程 switch | Angular 新手練功日誌

· 2 min

今天要介紹在模板中,如何使用 switch 條件語句來控制顯示的內容。 目前主要有兩種寫法:

@switch#

@switch (條件):根據條件值選擇顯示內容。

fallthrough 指的是當某個 case 執行完後,沒有使用 break 或 return 等語句,程式會繼續執行下一個 case 的內容。

@switch (status) {
@case ('success') {
<div>成功</div>
}
@case ('fail') {
<div>失敗</div>
}
@default {
<div>未知狀態</div>
}
}

ngSwitch#

舊版的寫法,使用 ngSwitch 指令來實現條件切換。

<div [ngSwitch]="fruit">
<div *ngSwitchCase="'apple'">蘋果</div>
<div *ngSwitchCase="'banana'">香蕉</div>
<div *ngSwitchCase="'orange'">柳橙</div>
<div *ngSwitchDefault>未知水果</div>
</div>

*ngIf一樣,ngSwitch 指令也需要引入 CommonModule

// 子模組
...
import { CommonModule } from '@angular/common';
@NgModule({
...
imports: [CommonModule],
...
})

獨立元件可只引入 NgSwitch

// 獨立元件
import { CommonModule } from '@angular/common';
import { NgSwitch } from '@angular/common';
@Component({
...
// imports: [CommonModule],
imports: [NgSwitch],
...
})

在 Angular 22 後,ngSwitch 會正式棄用,僅建議在舊專案中使用。

專案製作#

今日目標:練習事件觸發,按下按鈕時,可以增加待辦清單數量

day 11 分享

結論#

今天介紹了兩種在 Angular 模板中使用 switch 條件語句的方法:@switch 語法和舊版的 ngSwitch 指令。 明天介紹如何在模板中使用迴圈語句來顯示列表內容。