Angular 2 - Passing Component Data: Child to Parent

Passing Component Data: Child to Parent

The image below describes how to configure your components to pass data from a child component to a parent component.


The diagram purposefully lists the app.component.html and .ts files on top, as they are both the root component and the parent component to the header component.html and .ts files, listed on the bottom.

Working from the bottom up (child to parent):

In header.component.html (line 27) the button has a click event attached to it and fires the fireYellEvent($event) function, passing the event as an argument.

In header.component.ts (line 13) the fireYellEvent() is defined, and fires the emit() and again, passes the event as an argument. On line 12 the onYell variable is spec'd as an instance of the EventEmitter() method (and needs to be added in the import statement on line 1, don't forget!)

On line 3 of app.header.html - the parent component - (onYell)="yell($event)" is setup as a listener (since the code in the header.component.ts was spec'd as an instance of the EventEmitter(), then (onYell)="yell($event)" is very much a "listener").

In app.component.ts on line 14 the yell(e) event is simply defined here as an alert box, which gets called from the button click back in app.header.html.

Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/angular2/angular-2-passing-component-data-child-to-parent/