
Sharing data between child and parent components with Input and Output
In Angular, @Input() and @Output() are decorators that facilitate communication between parent and child components. @Input() allows passing data from parent to child, enabling component property binding. Conversely, @Output() emits events from child to parent, facilitating custom event handling. These decorators enhance component modularity and interactivity in Angular applications.
Data sharing from parent to a child component (Input)
Following is the approach to using Input for parent-to-child component communication:
In the parent component's template, use the child component and bind the property you want to pass "yourProperty" to the child component using property binding.
In the parent component's TypeScript file, you can set the value of the "title" property to pass it to the child component.
Now, the child component will receive the " title " value and display it in its template.
Parent Component
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<app-child-component [yourProperty] = "title"></app-child-component>`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title: String = 'Sending data to a child component';
}
Child Component
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child-component',
template: `<p>{{yourProperty}}</p>`,
styleUrls: ['./child-component.component.css']
})
export class ChildComponentComponent {
@Input() yourProperty: String = '';
}
Sharing data from a child to a parent component (Output)
Ensure to import the "Input" statement at the top of your component file.
Inside your component class, declare the property you want to receive from the parent component "yourProperty" using the @Input decorator. The property should have the same name as the one you'll use in the parent component.
Parent Component
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<app-child-component (exampleEvent)="addItem($event)"></app-child-component>
<p>{{title}}</p>`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title: String = '';
addItem(value: String): void {
this.title = value;
}
}
Child Component
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child-component',
template: `<button (click) = "displayText()">Display Text</button>`,
styleUrls: ['./child-component.component.css']
})
export class ChildComponentComponent {
@Output() exampleEvent = new EventEmitter();
displayText() {
this.exampleEvent.emit("Sending data to a parent component");
}
}