Creating Highly Reusable Angular Components
Child to parent component communication in Angular 6.0
Having components that can take care of routine functionality is a core concept to modern web development, regardless of your framework. This often means having our children component send information back to our parent. (like selecting a contact from an address book)
Today we look how use the EventEmitter
in Angular to dispatch events back up to parent components.
@Output Decorator
Import Output
from @angular/core
.
This will expose a new output property for us to bind to on the template on the parent component called “itemSelected”
In our child component define the Ouptput variable
@Output itemSelected = ...
EventEmitter
Import EventEmitter
from @angular/core
as well.
The EventEmitter
is a special class we get from Angular that will emit
our Event up to our parent component. We’ll set a new EventEmitter
to the value of our Output property itemSelected
.
@Output itemSelected = new EventEmitter()
Lets wire it together!
In our child component, we will define a local method when the component is clicked. On this local method, we will then call our Output
event’s emit()
method.
This will shoot our value back up to the parent component where we can further process the information, like adding the selected value to our address book.
On the child component Template
We’ll bind to the click event when a user selects a given item in our list (child) component. The only responsibility this component has is to render a list and tell our parent which one was selected
<div (click)="onClick(item)">{{item.name}}</div>
On the child component TypeScript
Define the method onClick
to catch the value selected, and inform our parent via the emit
method.
//In the child component, we pass the value to our local method
onClick(value){//send the value back to our parent's function
this.itemSelected.emit(value);
}
On the parent component template
/*we'll bind our parent's function to the output property we created called "itemSelected" on the child. Be sure you are passing the event to the local parent's method with "$event".*/<div (itemSelected)="selected($event)"></div>
Log the selected item on the parent component typescript
selected(item){
console.log(item)
}