首页 > 解决方案 > Angular:在带有 ngTemplateOutlet 的 ng-template 上下文的组件模板中使用对象文字的性能影响

问题描述

将上下文传递给 ng-template 时,在模板中使用对象字面量对性能有何影响?

<ng-container *ngTemplateOutlet="template;context:{ field: value };"></ng-container>

相对于:

<ng-container *ngTemplateOutlet="template;context:context;"></ng-container>

context = { field: value }

变更检测是否会在第一种情况下更频繁地运行,因为它(可能)创建了一个新对象?

https://github.com/angular/angular/blob/c2868de25a0fe4e14e4da4aae6aa2d5867711d05/packages/common/src/directives/ng_template_outlet.ts

  /**
   * We need to re-create existing embedded view if:
   * - templateRef has changed
   * - context has changes
   *
   * We mark context object as changed when the corresponding object
   * shape changes (new properties are added or existing properties are removed).
   * In other words we consider context with the same properties as "the same" even
   * if object reference changes (see https://github.com/angular/angular/issues/13407).
   */
  private _shouldRecreateView(changes: SimpleChanges): boolean {
    const ctxChange = changes['ngTemplateOutletContext'];
    return !!changes['ngTemplateOutlet'] || (ctxChange && this._hasContextShapeChanged(ctxChange));
  }

从这一点来看,我会说它确实有所作为,因为如果"ngTemplateOutletContext"changes. 如果它在模板中被定义为对象字面量,它就会一直存在。这假设每个周期都会创建一个新对象。这个假设是错误的吗?

标签: angularangular-template

解决方案


推荐阅读