Angular组件TS文件获取同组件<ng-content>元素返回undefined的原因
问题原因及解决思路
核心原因
ng-content本身不能作为查询目标:ng-content是Angular内容投影的占位符,不会被渲染成真实DOM元素,你给它添加的#action模板变量没有实际意义,无法关联到任何可查询的内容。@ContentChildren的作用是查询父组件投影到当前组件内的子元素,而非ng-content占位符本身。- 查询目标标记位置错误:你把
#action加在了当前组件的ng-content上,但Angular不会将这个变量传递给投影进来的内容。正确的做法是在父组件中给需要投影的元素添加#action,而不是当前组件的ng-content标签上。 - 生命周期时机问题:即使查询方式正确,若在
ngOnInit中直接访问content,也会因内容投影未完成得到undefined,必须在ngAfterContentInit钩子中访问,此时内容投影已完成。
修正示例
当前组件(如AppComp1)HTML
<div> <ng-content></ng-content> <app-comp2></app-comp2> </div>
父组件中使用当前组件时,给投影元素加标记
<app-comp1> <!-- 在这里给投影的元素添加#action --> <button #action>操作按钮</button> </app-comp1>
当前组件TS代码(添加生命周期钩子)
import { Component, ContentChildren, QueryList, ElementRef, AfterContentInit } from '@angular/core'; @Component({ selector: 'app-comp1', templateUrl: './comp1.component.html' }) export class Comp1Component implements AfterContentInit { @ContentChildren('action') content: QueryList<ElementRef>; ngAfterContentInit() { // 此时可正常获取投影的元素 console.log(this.content); } }
内容的提问来源于stack exchange,提问作者Sarah Mandana
相关产品推荐
相关产品推荐

