问题描述
具有以下DOM代码段:
<ng-app>
<ng-comp1></ng-comp1>
<ng-comp2>
<ng-comp3></ng-comp3>
</ng-comp2>
<ng-comp1></ng-comp1>
</ng-app>
我想从ng-comp3
列出DOM文档中的所有组件ng-comp1
。有办法吗?
ViewChildren
仅列出ng-comp3
内部的组件。
document.querySelector
列出DOM元素,而不是组件。
解决方法
简短的回答是“不,您不能直接列出它们”。
另一方面,您可以将ng-app
注入您的ng-comp3
组件中,并通过ng-comp1
与ng-app
进行交互。
@Component({
selector: 'inner-hello',template: `<h1>Hello {{name}}!</h1>`,styles: [`h1 { font-family: Lato; }`]
})
export class InnerHelloComponent implements AfterViewInit {
@Input() name: string;
constructor(@Inject(forwardRef(() => AppComponent)) private app: AppComponent) {
console.log(app.name);
}
ngAfterViewInit() {
// Here you will be able to access your ViewChild
}
}
别忘了ViewChild
被解雇之前,ViewChildren
和ngAfterViewInit
不会被填充
可能已经注意到,这个想法是在ng-comp1
组件中查询ng-app
,将其存储在公共变量中,然后从ng-comp3
访问它。在我的示例中,以相同的方式访问属性name