Thursday, March 16, 2017

the EventEmitter in Angular2

Let's say you want to have a component talk up to a component wrapping it or even old Angular 1 code wrapping Angular 2 code and trigger a TypeScript method or a JavaScript function like so:

wellWhatever(13, 42, 69, 86);

 
 

Alright, in your HTML where you call out to your component by its' selector, you'd do so like this:

<my-awesome-component (my-emitter)="wellWhatever($event.foo, $event.bar,
      $event.baz, $event.qux)"></my-awesome-component>

 
 

In the component you'd define the Output inside the component but outside any one method the same way you would any other component-wide variable. Do note the discrepancy between kebab case above and camel case here.

@Output() myEmitter = new EventEmitter<any>();

 
 

Somewhere in your component you'd actually use the Output.

this.myEmitter.emit({
   foo: 13,
   bar: 42,
   baz: 69,
   qux: 86
});

 
 

If you are doing the components wrapping components nesting thing only the outermost component should be bootstrapped in the module wrapping it yet one level up as if you bootstrap everything it sabotages the event emitters. I learned this the hard way.

 
 

Addendum 5/30/2017: Output, EventEmitter get looped in from: from '@angular/core';

No comments:

Post a Comment