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

Angular中ContentChild获取元素返回undefined问题排查

Angular中ContentChild获取投影元素返回undefined的解决办法

错误原因

你将@ContentChild装饰器用在了错误的组件中。#appHeader元素是投影到<app-card>组件的内容插槽里的,只有<app-card>组件能通过@ContentChild获取到这个元素,而你的代码把@ContentChild写在了ContentProjectionComponent中,所以获取结果必然是undefined。

修正方案

1. 修改<app-card>组件

将获取投影元素的逻辑移到AppCardComponent中:

import { Component, ElementRef, AfterContentInit, ContentChild, Renderer2 } from '@angular/core';

@Component({
  selector: 'app-card',
  templateUrl: './card.component.html',
  styleUrls: ['./card.component.less']
})
export class AppCardComponent implements AfterContentInit {

  @ContentChild('appHeader') headerElem: ElementRef;

  constructor(private renderer: Renderer2) { }

  ngAfterContentInit() {
    // 添加非空判断,避免投影内容不存在时报错
    if (this.headerElem) {
      this.renderer.setStyle(this.headerElem.nativeElement, "font-size", "120px");
    }
  }
}

2. 调整ContentProjectionComponent的模板与代码

确保ContentProjectionComponent的模板正确包含<app-card>及投影内容:

<h1>Content Children - Work With Projected Content</h1>
<app-card>
  <h1 header #appHeader>My Damn Header</h1>
</app-card>

同时简化ContentProjectionComponent的代码(移除无效的@ContentChild和相关逻辑):

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-content-projection',
  templateUrl: './content-projection.component.html',
  styleUrls: ['./content-projection.component.less']
})
export class ContentProjectionComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }
}

注意事项

  • @ContentChild仅能获取当前组件自身内容投影中的元素/指令,元素必须通过<ng-content>投影到当前组件内部。
  • 访问nativeElement前务必添加非空判断,防止因投影内容未提供导致的空指针错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:35:35