[英]Angular: possible to queries elements of all DOM from a specific component?
使用下面的 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-app
与ng-comp1
交互。
@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-app
组件中查询ng-comp1
,将其存储在公共变量中并从ng-comp3
访问它。 与我在示例中访问属性name
方式相同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.