0
votes

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

2
Can you show us the code that you tried? - ConnorsFan
why do you want to do this way ? :) - rijin
@rijin because i want to call a method of that component and these components are coming from a lib, i cannot modify the code - Anto Antony

2 Answers

0
votes

@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.

0
votes

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