Angular:ngAfterViewInit中QueryList获取子指令仍为undefined的问题
问题原因与解决方案
问题出在你用了ViewChildren,它只能查询当前指令/组件自身模板内的直接子元素或指令。而你的<p appDirTwo>是放在父指令所在的<main>标签内部的内容投影区域,不属于父指令的模板,所以ViewChildren无法捕获到这些子指令,导致QueryList为undefined。
解决方法:改用ContentChildren
将@ViewChildren替换为@ContentChildren,它专门用于查询内容投影进来的子元素或指令,正好匹配你的场景。
修改后的父指令代码:
import { AfterViewInit, Directive, QueryList, ContentChildren, // 替换ViewChildren为ContentChildren } from '@angular/core'; import { DirTwoDirective } from './dir-two.directive'; @Directive({ selector: '[appDirOne]', }) export class DirOneDirective implements AfterViewInit { @ContentChildren(DirTwoDirective) childDirectives: QueryList<DirTwoDirective>; // 这里改用ContentChildren constructor() {} ngAfterViewInit() { console.log(this.childDirectives); // 现在能正常获取到QueryList了 console.log(this.childDirectives.length); // 会输出4,对应4个appDirTwo指令 } }
补充说明
ContentChildren的初始化时机是在ngAfterContentInit生命周期钩子,不过在ngAfterViewInit中也能正常访问,因为后者的执行时机晚于前者。- 如果需要监听子指令的变化(比如新增/删除),可以调用
childDirectives.changes.subscribe()来订阅变化事件。
内容的提问来源于stack exchange,提问作者Sam L
相关产品推荐
相关产品推荐

