「當我們真的有改變需要渲染的資料時,才進行渲染」,我們也可以稱他為一種「回應變化」的處理方式,也就是每次渲染,都一定會有一個主動的變化,也是我們常常講的「reactidve programming」的一種應用。 Angular 借用了 solid.js 提出的 signal 概念,我們可以把它想像成是一種資料的「訊號」,只有當這個「訊號」有發送的時候,我們才進行回應 (也就是畫面渲染),如此一來就可以提高整體應用程式的效率!
定義Signal Signal Html html
1 2 3 4 5 6 <div style="font-size: 80px;">{{count()}}</div> <div class="btn_group"> <a (click)="set()" class="button set_button">設置</a> <a (click)="add()" class="button add_button">+1</a> <a (click)="minus()" class="button minus_button">-1</a> </div>
Signal TS 設置更新邏輯 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 import { Component, signal } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [CommonModule, RouterOutlet], templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { count = signal(1) // 設置初始數 set() { this.count.set(1) } // Add增加 add() { this.count.update(c => c + 1) } // Minus減少 minus() { this.count.update(c => c - 1) } }
計算computed Singal computed() 會回傳一個 readonly signal,且在呼叫時需要傳入一個 callback function,在此 function 內的 signal 發生變化時,這個 callback function 就會自動被呼叫,因此我們可以在 signal 有變化時,才去根據來源 signal 產生新結果,
引入 computed, signal 1 2 3 import { Component,computed, signal } from '@angular/core'; ... counter = signal(0);
TS 定義count=>signal(值) computed(() => { return … })
1 2 3 4 5 6 7 8 9 10 11 12 import { Component,computed, signal } from '@angular/core'; export class HomeComponent { count = signal(2) countPlus = computed(() => { return this.count() * this.count() }) add() { this.count.update(() => this.count() * this.count()) } }
Html
1 2 3 4 5 6 7 8 9 10 11 <div class="container"> <div class="flex_center"> <p class="flex_center">compouted works!</p></div> <div class="flex_center"> <div class="flex_center">{{ count() }}</div> <div class="flex_center">{{ countPlus() }}</div> </div> <div class="flex_center" > <a class="button add_button" (click)="add()">+1</a> </div> </div>