随着信号的添加和它们改进更改检测的方式,我想知道是否应该开始只使用信号(而不是类变量),以便在组件模板中显示数据以提高性能?
使用变量更新模板中的数据:
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
@Component({
selector: 'app-foo',
standalone: true,
imports: [CommonModule],
template: `<div>Message from the component: {{ message }}</div>`,
})
export class TwoComponent {
public message = 'Hello World!';
// Random way to update the message and automatically trigger Change Detection
public changeMessage(value: string): void {
this.message = value;
}
}
VS使用信号更新模板中的数据:
import { CommonModule } from '@angular/common';
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-foo',
standalone: true,
imports: [CommonModule],
template: `<div>Message from the component: {{ message() }}</div>`,
})
export class FooComponent {
public message = signal('Hello World!');
// Random way to update the message signal and automatically trigger Change Detection
public changeMessage(value: string): void {
this.message.set(value);
}
}
In this example I have a very basic template and a string, of course the Change Detection impact could be bigger for complex objects, arrays or complex views. Also, in many situations the Signal might exist in your Service/Store layer.个
UPDATE
根据我的理解,如果您只使用信号,则可以将更改检测配置为OnPush
,这也可能会提高性能.