Call a function on child component from parent

1.4k Views Asked by At

I'm looking for a way to call a function on a child component from the parent component. I have a ModalComponent(parent) and MessageComponent (child). I need to enable communication between them. It was possible to do in Angular 1 with the use of a shared service. I wonder if Angular 2 has something more to offer in a situation like this. Anyway, would you please take a look?

Here are the relevant routes:

  { 
    path: 'modal', 
    component: ModalComponent, 
    outlet: 'modal',
    children: [
      {
        path: 'message',
        component: MessageComponent
      }
    ]
  }

ModalComponent has a button in its template and a router-outlet(to host MessageComponent). I need to press the button in ModalComponent's template and trigger a function on MessageComponent.

Here's ModalComponent:

@Component({
  template: `
   <div class="footer">  
    <button (click)="action('accept')">Accept</button>
   </div>
  `,
})

export class ModalComponent {
 action(type: string){
   switch(type){
     case 'accept':
       break;
   }
 }
}

Here's MessageComponent:

@Component({
  template:`
    <div>String sent: <b>{{actionName}}</b></div>
    `,
})
export class MessageComponent {
  actionName: string;
  action(name){
    this.actionName = name;
  }
}

HERE'S PLUNKER

2

There are 2 best solutions below

0
On BEST ANSWER

You can do this with an EventEmitter.

Define an emitter in your component

@Output() public myEmitter = new EventEmitter();

Trigger the emitter in the parent

this.modal.content.myEmitter.next(this.id);

Do something in the modal

this.myEmitter.take(1).subscribe((id: number) => {
  //do something
});
0
On

You can use the @viewChild property:

@Component({
 template:`<div>String sent: <b>{{actionName}}</b></div>`,
})
export class MessageComponent {

  @ViewChild(MessageComponent)
  private messageContent : MessageContent;

  actionName: string;
  action(name){
    this.actionName = name;
  }
}

Then you have a reference to MessageComponent in your parent component and you can use any functions on it.