You need to enable JavaScript to run this app. Angular11自定义结构指令:输入setter中ng-template为undefined触发运行时报错
优惠活动
大模型
产品
解决方案
定价
更多

Angular11自定义结构指令:输入setter中ng-template为undefined触发运行时报错

自定义结构指令setter内空引用异常的根因与规范实现

异常产生的根本原因

  • 输入赋值无统一等待机制
    Angular对指令@Input属性的赋值流程是按顺序逐次执行的,严格匹配语法糖展开后模板上的绑定书写顺序,不会等所有输入全部赋值完成后再触发对应setter。
    你写的结构指令*appMyDirective="(data$ | async)!; loading: loadingTemplate"经过语法糖编译展开后,等价于以下模板结构:
    <ng-template 
      appMyDirective 
      [appMyDirective]="(data$ | async)!" 
      [appMyDirectiveLoading]="loadingTemplate"
    >
      <div></div>
    </ng-template>
    
    赋值流程会先触发位置靠前的[appMyDirective]主输入setter,此时位于后面的[appMyDirectiveLoading]还未完成赋值,因此在主setter中访问this.appMyDirectiveLoading会得到undefined。
  • 报错的触发链路
    当createEmbeddedView收到的第一个模板引用参数为undefined时,Angular内部实现会尝试调用该空值上的实例方法,最终抛出ERROR TypeError: Cannot read property 'createEmbeddedView' of undefined错误,和你遇到的异常完全匹配。
  • ngOnInit逻辑可正常运行的原因
    ngOnInit的触发时机是所有输入属性完成首次赋值之后。此时无论模板上的输入绑定顺序如何,所有输入值都已经完成初始化,因此可以正常获取到加载态模板引用并完成视图创建。

注意:你原代码ngOnInit中的console.log语句漏写了this前缀,实际运行时会触发未定义变量的报错,正确写法应为console.log(this.appMyDirectiveLoading)。

符合Angular开发规范的实现方式

核心解决思路是彻底解耦输入setter的顺序依赖,通过统一的渲染闸门校验所有依赖是否就绪,再执行视图操作,避免因为绑定顺序变化触发空引用错误。

实现要点

  • 每个输入setter仅完成值的本地存储,不直接执行视图操作,存储完成后触发统一的渲染判断逻辑
  • 统一渲染方法中增加全量判空,只有当主输入数据、加载态模板引用、视图容器全部就绪时,才执行视图清除与创建操作
  • 在ngOnInit钩子中主动触发一次渲染判断,覆盖初始场景
  • 这种实现方式不依赖输入的书写顺序,无论模板上的绑定位置怎么调整,都能稳定运行,符合结构指令的通用设计规范

修正后的指令实现代码

import { Directive, Input, OnInit, TemplateRef, ViewContainerRef } from '@angular/core';

interface DataWrapper {
  loading: string;
}

interface LoadingContext {
  $implicit: string;
}

@Directive({
  selector: '[appMyDirective]'
})
export class CustomDirectiveDirective implements OnInit {
  // 本地缓存输入值
  private _directiveData: DataWrapper | null = null;
  private _loadingTemplate: TemplateRef<LoadingContext> | null = null;

  constructor(
    private _viewContainer: ViewContainerRef,
    // 注入结构指令默认绑定的宿主模板
    private _hostTemplateRef: TemplateRef<any>
  ) {}

  // 加载态模板输入
  @Input()
  set appMyDirectiveLoading(tpl: TemplateRef<LoadingContext>) {
    this._loadingTemplate = tpl;
    this.triggerRender();
  }

  // 主绑定输入
  @Input()
  set appMyDirective(data: DataWrapper | null) {
    this._directiveData = data;
    this.triggerRender();
  }

  ngOnInit(): void {
    this.triggerRender();
  }

  // 统一渲染闸门:依赖全就绪才执行视图操作
  private triggerRender() {
    // 任意依赖缺失直接退出
    if (!this._directiveData || !this._loadingTemplate || !this._viewContainer) {
      return;
    }

    this._viewContainer.clear();
    this._viewContainer.createEmbeddedView(this._loadingTemplate, {
      $implicit: this._directiveData.loading
    });
  }
}

内容的提问来源于stack exchange,提问作者Riaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.30 06:57:07