更改默认变更检测策略

Change default change detection strategy

如何设置默认变化检测策略为OnPush?可以全局设置吗?

我想避免将这一行添加到每个组件

@Component({
    ...
    changeDetection: ChangeDetectionStrategy.OnPush,
    ...
})

更改检测策略只能按组件或指令定义,不能全局定义。

不鼓励使用自定义装饰器,因为即将推出的离线模板编译器将不支持它。

可以在 CLI 中将更改检测策略设置为 OnPush,以便新生成的组件将这样设置。

ng generate component test --changeDetection=OnPush

您还可以在 angular.json 中将该值设置为默认值,这样您就不需要每次都设置标志:

// angular.json
{
  //...
  "schematics": {
    "@schematics/angular": {
      "component": {
        "changeDetection": "OnPush"
      }
    }
  }
}