简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM