You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中使用注入令牌获取ContentChild始终为undefined问题

解决内容投影中通过注入令牌获取实例的问题

问题原因

@ContentChild 用于查询内容投影中的组件或指令实例,无法直接通过注入令牌(InjectionToken)获取对应值。当前写法不符合Angular内容查询规则,因此始终获取不到目标实例。

解决方案

1. 创建承载注入令牌的指令

定义一个指令,将BUTTON_ENABLED_DIALOG注入令牌与指令关联,让内容投影元素应用该指令后,可通过指令实例获取令牌对应的对象:

import { Directive, Inject, Optional } from '@angular/core';
import { BUTTON_ENABLED_DIALOG, IButtonEnabledDialog } from './your-path';

@Directive({
  selector: '[buttonEnabledDialog]',
  exportAs: 'buttonEnabledDialog'
})
export class ButtonEnabledDialogDirective {
  constructor(@Optional() @Inject(BUTTON_ENABLED_DIALOG) public dialog: IButtonEnabledDialog) {}
}

2. 在调用组件中应用指令并提供令牌值

在调用组件的providers中配置BUTTON_ENABLED_DIALOG的具体实现,同时在模板里给内容投影元素加上指令:

// 调用组件的providers配置
providers: [
  {
    provide: BUTTON_ENABLED_DIALOG,
    useValue: { /* 此处填入IButtonEnabledDialog的具体实现 */ }
  }
]

模板代码:

<app-your-dialog>
  <div buttonEnabledDialog>
    <!-- 内容投影的内容 -->
  </div>
</app-your-dialog>

3. 在目标组件中查询指令实例

将原组件的@ContentChild查询目标替换为创建的指令,再通过指令实例获取令牌对应的值:

import { ContentChild, OnInit } from '@angular/core';
import { ButtonEnabledDialogDirective } from './your-path';

@ContentChild(ButtonEnabledDialogDirective, { static: true }) contentDirective?: ButtonEnabledDialogDirective;

ngOnInit() {
  if (this.contentDirective?.dialog) {
    // 处理获取到的IButtonEnabledDialog实例
  }
}

核心逻辑说明

通过指令作为桥梁,将注入令牌的实例绑定到指令上,让@ContentChild能够查询到内容投影元素关联的指令实例,进而获取令牌对应的实现对象。需确保内容投影元素已应用指令,且调用组件正确配置了注入令牌的提供者。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 04:15:08