Check out this stackblitz sample project for experimenting with parent-child data communication, utilizing the @Input()
and @Output()
functionalities
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'child',
template: `
<h1>Greetings {{ name }}! This is the child component</h1>
<button (click)="sendEventToParent()">Send information to parent</button>
`,
styles: [
`
h1 {
font-family: Lato;
}
`
]
})
export class ChildComponent {
@Input() name: string;
@Output() eventFromChild: EventEmitter<string> = new EventEmitter();
sendEventToParent(): void {
this.eventFromChild.emit('data from child');
}
}
This section presents the parent component HTML named child
<child name="{{ name }}" (eventFromChild)="onEvent($event)"></child>
<h1>This is the parent component</h1>
<p>{{dataFromChild}}</p>
The event binding code snippet appears as follows
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
dataFromChild = '';
onEvent(event): void {
this.dataFromChild = event;
}
}