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

Angular中@ViewChild获取Directive始终为undefined问题及解决

问题:Angular组件内@ViewChild获取自定义指令始终返回undefined

在开发复杂Angular项目时,遇到以下异常情况:

  • 在ConverterViewComponent组件中,使用@ViewChild(PlaceholderDirective)获取自定义指令时始终返回undefined,@ViewChildren获取的指令列表为空;
  • 但使用@ViewChild("test")获取元素引用能正常返回ElementRef;
  • 组件HTML中已为元素添加app-placeholder指令,该指令用于获取ViewContainerRef以动态创建组件;
  • 其他组件通过相同方式创建ConverterViewComponent时,PlaceholderDirective能正常工作,仅在ConverterViewComponent内部获取该指令时出现问题。

已尝试的解决方法

  • 使用@ViewChildren(PlaceholderDirective)并监听changes事件,无任何触发;
  • 为@ViewChild(PlaceholderDirective)设置setter,仅被调用一次且参数为undefined;
  • 使用@ContentChild(PlaceholderDirective),同样返回undefined。

解决方案

经排查,问题根源是未在app.module.ts中正确导入PlaceholderDirective。将其添加到declarations和providers数组后,问题解决。代码示例如下:

import { PlaceholderDirective } from './converter-submodule/utilities/placeholder-directive';
[...其他导入]

@NgModule({
  declarations: [
    PlaceholderDirective,
    InfoComponent,
    ConverterViewComponent,
    [...其他声明]
  ],
  imports: [
    [...其他导入]
  ],
  providers: [
    PlaceholderDirective,
    [...其他提供者]
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 07:41:24