问题描述: 在Angular中使用ViewChildren获取动态组件时,始终返回undefined。
解决方法:
确保动态组件已经正确地被添加到父组件中。 例如,在父组件的模板中使用ng-container和ngTemplateOutlet来动态加载组件:
确保在动态加载组件之前,已经将动态组件添加到dynamicComponent模板中。
使用AfterViewInit生命周期钩子来获取动态组件。 在父组件中,实现AfterViewInit接口,并在ngAfterViewInit方法中获取动态组件。
import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
import { DynamicComponent } from './dynamic.component';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent implements AfterViewInit {
@ViewChildren(DynamicComponent) dynamicComponents: QueryList;
ngAfterViewInit() {
console.log(this.dynamicComponents); // 获取到动态组件的QueryList
}
}
如果动态组件是通过ngIf或ngFor条件渲染的,请确保在获取动态组件之前,动态组件已经被渲染到DOM中。 这可以通过使用setTimeout来延迟获取动态组件,以确保组件已经被渲染到DOM中。
import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
import { DynamicComponent } from './dynamic.component';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent implements AfterViewInit {
@ViewChildren(DynamicComponent) dynamicComponents: QueryList;
showComponent = true;
ngAfterViewInit() {
setTimeout(() => {
console.log(this.dynamicComponents); // 获取到动态组件的QueryList
});
}
}
通过以上方法,您应该能够成功获取到动态组件的QueryList,并进行后续的操作。
上一篇:Angular动态组件属性绑定