With the DOM snippets below:
<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. There is a way for that ?
ViewChildren
list only components inside ng-comp3
.
document.querySelector
list DOM element, not the component.
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
.
@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
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
. The same way I am accessing the property name
in my example
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.