Angular2 Fire EventEmitter for parent component

I am trying to fire an event from a child component to a 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 can I make this work?

+4
source share
1 answer

You define EventEmitterin the 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 as follows:

@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

+5
source

Source: https://habr.com/ru/post/1662685/


All Articles