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
You can do this with an EventEmitter.
Define an emitter in your component
Trigger the emitter in the parent
Do something in the modal