0
votes

How to access (call certain methods) of child components of (2) children componenet s of some parent (container) component; i.e, Having ParentCmp holding inside template two children components (their selectors + template refs), and call certain methods of LoadingPanels inside those (two children) components:

ParentCmp.html: ....

<child1 #child1></child1>
<child2 #child2></child2>

ParentCmp.ts:

  @ViewChild('child1', read: ComponentRef<child1Cmp>) child1Cmp: ComponentRef<InvitationsBarComponent>;
  @ViewChild('child2') meetingsBarCmp: Child2Cmp;
...

child1Cmp.instance.loadingPnl.load(() => {....});
child2Cmp.loadingPnl.load(() => {....});

?

2
Why do you need to do this? Could they communicate via a service instead? See angular.io/guide/component-interactionjonrsharpe

2 Answers

0
votes

Give this a try:

import { Component, ViewChild } from '@angular/core';
import { Child1Component } from './child1/child1.component';
import { Child2Component } from './child2/child2.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild(Child1Component) child1: Child1Component;
  @ViewChild(Child2Component) child2: Child2Component;

  ngAfterViewInit() {
    this.child1.child1Method();
    this.child2.child2Method();
  }

}

And in your Template:

<child1></child1>

<child2></child2>

PS: You can be sure to get access to the Child Component Instances in the ngAfterViewInit as that's when the view would be completely loaded.


Here's a Working Sample StackBlitz for your ref.

0
votes

You could leverage ViewChild to call a method of child 2 in the parent component. Have a look at the following.

Parent:

import { Component, ViewChild } from '@angular/core';
import { Child1Component } from './child1/child1.component';

@Component({
  selector: 'my-app',
  templateUrl: '
        <div>
        <child1 #Child1Component></child1>
        </div>',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild(Child1Component) child1?: Child1Component;

  customMethod() {
    this.child1?.child2?.someMethodOfChild2();

  }

Child 1:

import { Component, ViewChild } from '@angular/core';
import { Child2Component } from './child2/child2.component';

@Component({
  selector: 'child1',
  templateUrl: '
        <div>
        <child2 #Child2Component></child2>
        </div>',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild(Child2Component) child2?: Child2Component;

}