I have a hierarchy of components as follows.
Parent Component A
-> Child Component B (child of component A)
-> Child component C (child of component B)
How do we get the reference to component c from indirect parent component A? I tried to access the child component C from parent using view child but getting undefined.
note: the child components are from some third party lib. I cannot alter those files
stackblitz.com/edit/angular-bpmwxz
@ViewChild
will work. We don't know how this is organized or how Component B's template works, though, so if there's a template directive Component B is using you'd have to @ViewChild(ComponentCTypeToken)
instead of using template variables.
However, as we don't know how Component B is rendering templates (or how these components are used), if Component C is nested in Component B in Component A's template, there's a good chance Component B is rendering its own template via content projection; in that case, it's need to be a @ContentChild
instead.
You can solve this by chained reference.
Parent Component A {
holds the reference of Chil Component B;
calls the ChildB.function();
}
-> Child Component B {
holds the reference of Child Component C <-- hope this is the library component
calls the ChildC.function();
}
-> Child component C {
function();
}
Code sample
export class AppComponent {
name = 'Angular';
@ViewChild(SampleOneComponent)
sampleOne: SampleOneComponent;
getInstanceOfChild() {
this.sampleOne.getInstanceOfChild();
}
}
export class SampleOneComponent implements OnInit {
@ViewChild(SampleTwoComponent)
sampleOne: SampleTwoComponent;
constructor() { }
ngOnInit() {
}
getInstanceOfChild() {
this.sampleOne.libFn();
}
}
export class SampleTwoComponent implements OnInit {
title: string = "yeahhh";
constructor() { }
ngOnInit() {
}
libFn() {
console.log('Im in sample two');
}
}
Stackblitz url with chagnes https://stackblitz.com/edit/angular-jnhc5v
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.