[英]Angular: possible to queries elements of all DOM from a specific component?
With the DOM snippets below:使用下面的 DOM 片段:
<ng-app>
<ng-comp1></ng-comp1>
<ng-comp2>
<ng-comp3></ng-comp3>
</ng-comp2>
<ng-comp1></ng-comp1>
</ng-app>
I would like from ng-comp3
to list all components ng-comp1
in DOM document.我想从
ng-comp3
列出 DOM 文档中的所有组件ng-comp1
。 There is a way for that ?有办法吗?
ViewChildren
list only components inside ng-comp3
. ViewChildren
仅列出ng-comp3
组件。
document.querySelector
list DOM element, not the component. document.querySelector
列出 DOM 元素,而不是组件。
The short answer is "No, you cannot directly list them".简短的回答是“不,你不能直接列出它们”。
What you can do, on the other hand, is to have the ng-app
injected in your ng-comp3
component and interact with the ng-comp1
via the ng-app
.另一方面,您可以做的是将
ng-app
注入您的ng-comp3
组件中,并通过ng-app
与ng-comp1
交互。
I have put an example here 我在这里放了一个例子
@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
}
}
Don't forget that the ViewChild
and ViewChildren
do not get populated until ngAfterViewInit
gets fired不要忘记
ViewChild
和ViewChildren
在ngAfterViewInit
被触发之前不会被填充
The idea, as may have noticed, is to query for ng-comp1
in the ng-app
component, store that in a public variable and access it from the ng-comp3
.可能已经注意到,这个想法是在
ng-app
组件中查询ng-comp1
,将其存储在公共变量中并从ng-comp3
访问它。 The same way I am accessing the property name
in my example与我在示例中访问属性
name
方式相同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.