随着信号的添加和它们改进更改检测的方式,我想知道是否应该开始只使用信号(而不是类变量),以便在组件模板中显示数据以提高性能?

使用变量更新模板中的数据:

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,这也可能会提高性能.

推荐答案

在您的示例中,changeMessage()方法的代码不会计划更改检测周期.

目前,ANGLE使用ZoneJS来调度变更检测(CD)周期.ZoneJS Money--修补异步DOM API和大多数DOM事件.

要调用changeMessage(),您需要添加一些click事件处理程序或一些仅用于setTimeout()调用的函数,因为DOM事件和异步API是由ZoneJS修补(和监视)的,ANGLE将知道是时候运行CD周期了.

因此,触发更改检测的不是changeMessage(),而是您生成的呼叫changeMessage()的事件.你可以拿read more about Angular Change Detection here美元.

ANGLE团队计划改善这种情况,采用OnPush策略的组件将不需要ZoneJS(它将显著提高性能).

你现在能做的最好的事情是:

  • 在新的组件中使用OnPush策略;
  • 在新组件的模板中为变量使用信号.

OnPush既可以与信号一起使用,也可以与+async可见管一起使用.

Angular相关问答推荐

如果Angular 模块是独立的,为什么我不需要在App模块中使用RouterModule?

无法添加@angular/pwa

未触发HTTP拦截器

如何从URL中角下载图片?

找不到模块webpack dev服务器

Router.navigate() 在功能拦截器内不起作用

SignalR:协商有效,但消息未发送(.NET/Angular)

npm install命令在基本Angular 应用程序的天蓝色构建管道中失败

PrimeNG:如何以编程方式更改分页器中的选定页面?

在 kubernetes 上创建 Ingress 服务以将 springboot [后端] 连接到前端 [angular]

Angular:组件的内容投影访问数据

在ionic 5中获取url传递的参数

angular material日期 Select 器中的日期不正确

可从 Angular2 中的

Angular/RxJS 6:如何防止重复的 HTTP 请求?

Angular 2 - 事件列表

Angular 2如何让子组件等待异步数据准备好

在 webpack 构建中包含 git commit hash 和 date

Angular 2 可用的 yeoman 生成器

如何在 Angular 4 中翻译 mat-paginator?