Signals
创建并管理动态数据。
在 Angular 中,你可以使用 signals(信号)来创建和管理状态。Signal 是对某个值的轻量级包装器。
使用 signal 函数创建一个用于保存本地状态的信号
import {signal} from '@angular/core';
// Create a signal with the `signal` function.
const firstName = signal('Morgan');
// Read a signal value by calling it— signals are functions.
console.log(firstName());
// Change the value of this signal by calling its `set` method with a new value.
firstName.set('Jaime');
// You can also use the `update` method to change the value
// based on the previous value.
firstName.update((name) => name.toUpperCase());
Angular 会追踪信号在何处被读取以及何时被更新。框架利用这些信息执行额外的工作,例如使用新状态更新 DOM。这种随时间推移响应信号值变化的能力被称为响应式 (reactivity)。
计算表达式
computed 是一个基于其他信号产生其值的信号。
import {signal, computed} from '@angular/core';
const firstName = signal('Morgan');
const firstNameCapitalized = computed(() => firstName().toUpperCase());
console.log(firstNameCapitalized()); // MORGAN
computed 信号是只读的;它没有 set 或 update 方法。相反,当它所读取的任何信号发生变化时,computed 信号的值会自动更新
import {signal, computed} from '@angular/core';
const firstName = signal('Morgan');
const firstNameCapitalized = computed(() => firstName().toUpperCase());
console.log(firstNameCapitalized()); // MORGAN
firstName.set('Jaime');
console.log(firstNameCapitalized()); // JAIME
在组件中使用信号
在组件内部使用 signal 和 computed 来创建和管理状态
@Component({
/* ... */
})
export class UserProfile {
isTrial = signal(false);
isTrialExpired = signal(false);
showTrialDuration = computed(() => this.isTrial() && !this.isTrialExpired());
activateTrial() {
this.isTrial.set(true);
}
}
提示:想深入了解 Angular Signals 吗?请参阅《深入了解 Signals》指南以获取完整详情。
下一步
既然你已经学会了如何声明和管理动态数据,现在是时候学习如何在模板中使用这些数据了。