I am trying to fire an Event from the child component to the parent component.
@Component({
template:'<foo></foo>'
})
export class ParentComponent{
onDoSomething($event){
//do work here
}
}
@Component({
selector:'foo'
template:<button (click)="onClick($event)">MyButton</button>
})
export class ChildComponent{
myEvent eventName = new EventEmitter();
onClick(button){
this.eventName.emit(button);
}
}
How do i get this to work?
Prepare Child component to emit data Furthermore, we need to know that the child component uses the @Output() property to raise an event (by using an EventEmitter) to notify the parent of the change. @Output() is a decorator that marks a class field (that has to be named) as an output property.
Child to parent component If you want to pass data from the child component to the parent component use @Output() and EventEmitter. To pass data from the child to the parent, you have to emit it from the child.
You define an EventEmitter
in your child component with @Output
@Component({
selector:'foo',
template:`<button (click)="onClick($event)">MyButton</button>`
})
export class ChildComponent{
@Output() myEvent = new EventEmitter();
onClick(button){
this.myEvent.emit(button);
}
}
then you "subscribe" to this event in your parent component like this:
@Component({
selector: 'my-app',
template: `Hello World <foo (myEvent)="myEvent($event)"></foo>`,
directives: [],
providers: []
})
export class AppComponent {
myEvent($event){
console.log(1, $event);
}
}
Full example: http://plnkr.co/edit/MeQbC7Jbc8rprMF66aEF?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With