How to share the data between components in Angular 9?
Many times you will have the requirement of sharing the data between components. It can be a parent to child, child to parent, and separate parts. So let's understand this with the help of an example.
Parent To Child Component - any data from parent to child component can be shared with the help of @Input decorator.
Example
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: ``,
styleUrls: ['./parent.component.css']
})
export class ParentComponent{
parentMessage = "message from parent"
constructor() { }
}
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `Say {{ childMessage }}`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() childMessage: string;
constructor() { }
}
Child To Parent Component 1 - you can share the data from child
component to parent using @Output decorator.
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `Message: {{message}}`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
constructor() { }
message:string;
receiveMessage($event) {
this.message = $event
}
}
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `Send Message `,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
message: string = "Hello Testing!"
@Output() messageEvent = new EventEmitter();
constructor() { }
sendMessage() {this.messageEvent.emit(this.message) }
}