1

I have a parent component and inside there are 2 different child components. I need to call the second child component's function from the first child component when I click a link in the first child component.

So here is a basic diagram to explain better:

enter image description here

Naveen DA
  • 4,148
  • 4
  • 38
  • 57
sa_
  • 2,854
  • 3
  • 22
  • 29

1 Answers1

2

You could archieve this by means of ViewChild and Output

For example:

@Component({
  template: `
     <child-one (clicked)="handleClick()"></child-one>
     <child-two></child-two>
  `
})
export class ParentComponent {
   @ViewChild(ChildOneComponent)
   childOne: ChildOneComponent;

   handleClick(){
    this.childOne.doSomething();
   }
}

In this case:

  • clicked is an Ouput property of ChildOneComponent
  • doSomething is a public method

Another approach only ussing Output and a template variable

@Component({
  template: `
     <child-one (clicked)="childTwo.doSomething()"></child-one>
     <child-two #childTwo></child-two>
  `
})
export class ParentComponent {
   
}
Diego Montania
  • 322
  • 5
  • 12
Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
  • thanks for this, actually right now I'm trying to do this. Once I finish I'll write again. – sa_ Jul 18 '17 at 16:43
  • thanks, I finally managed with this way, also this one helped me too, https://stackoverflow.com/questions/41954484/communicate-between-two-child-components-in-angular-2 – sa_ Jul 18 '17 at 17:25
  • another solution is using a service between these 2 components, this is also mentioned at above link – sa_ Jul 18 '17 at 17:26
  • A service would be a better approach in the case that you want to exchange data between the components, and specially in the case that there is no parent-child relation. To just invoke a method, when an event is captured, this approach is ok – Jota.Toledo Jul 18 '17 at 17:33