In a previous post, we looked at sharing data from parent to child component. How do we go from child to parent? We use the @Output decorator.
Angular is really a one-way data flow. We can do two-directional with banana in a box (see a previous posting I did about this). Output allows us to emit from child to parent.
import { Component, Input, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: `<button (click)="clickChildButton()">Click this child button!</button>`
})
export class AppChildComponent {
clickChildButton() {
console.log('You clicked the child button!');
}
}
As you can see from the above, I have a button in my child component. When the user clicks the button, the click event is fired, which runs the clickChildButton method. Let’s see how to use that from the parent…
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `<app-child></app-child>`
})
export class AppComponent implements OnInit {
ngOnInit() {
}
}
I am using the child component inside the parent root component. This creates the parent/child relationship. If you run the application, you will see the button and when it is clicked, you should see the console message.
This is fairly straightforward, but what if we want to trigger a method in the parent component when the child component’s button is clicked?
For this functionality, we have to emit the button click from the child to the parent. This is why we have the EventEmitter imported. Let’s make the necessary child component changes.
import { Component, Input, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: `<button (click)="clickChildButton()">Click this child button!</button>`
})
export class AppChildComponent {
@Output() showChildInfo = new EventEmitter();
msg = 'You clicked the child button!';
childInfotoShow() {
this.showChildInfo .emit(this.msg);
}
}
Here we created a variable to hold the data (msg). We also created an emitter (showChildInfo) that will send an emit to the parent. We created a function (childInfotoShow) that we can call in an event like a click. This will emit the msg and pass the data value. SO what does the parent look like?
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `<app-child (showChildInfo)='showInfo($event)'></app-child>`
})
export class AppComponent implements OnInit {
ngOnInit() {
}
showInfo(info) {
console.log(info);
}
}
In our app-child element, we are binding an event to use the showChildInfo event. We call the showInfo method on the showChildInfo event. We then display the msg that was passed from the child in the console.
So, we can communicate between parents and children. The @Output decorator allows us to use events in a parent to display information from a child.
Happy Coding!
Clay Hess