JT1979
JT1979

Reputation: 181

Angular2 EventEmitter fire to parent component

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?

Upvotes: 5

Views: 7341

Answers (1)

eko
eko

Reputation: 40677

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

Upvotes: 6

Related Questions