Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 411
JT1979 Avatar asked Dec 02 '16 20:12

JT1979


People also ask

How do I send my child an event to a parent?

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.

How do you pass data from one component to another using EventEmitter?

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.


1 Answers

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

like image 50
eko Avatar answered Oct 09 '22 01:10

eko