If you want to share data from a child component to a parent component, you can use @Output()
and EventEmitter<>
.
Or if you are trying to share data between two unrelated components, you can use BehaviorSubject()
via a Service
; that also works for sharing data between parent and child components.
Child to parent: Sharing data using @Output()
and EventEmitter<>
.
parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
Message: {{ message }}
<app-child (messageEvent)="receiveMessage($event)"></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent{
constructor(){}
message: string;
receiveMessage($event){
this.message = $event
}
}
child.component.ts
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<button (click)="sendMessage()">Send message</button>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent{
message: string = "Hola, Mundo!";
@Output() messageEvent = new EventEmitter<string>();
constructor(){}
sendMessage(){
this.messageEvent.emit(this.message);
}
}
Unrelated components: Sharing data via a Service
data.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataService{
private messageSource = new BehaviorSubject('Original
message.');
currentMessage = this.messageSource.asObservable();
changeMessage(message: string){
this.messageSource.next(message)
}
}
home.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from
'src/app/shared/services/data.service';
@Component({
selector: 'app-home',
template: `
{{ message }}
`,
styleUrls: ['./sibling.component.css']
})
export class HomeComponent implements OnInit{
message: string;
constructor(private dataService: DataService){}
ngOnInit(){
this.dataService.currentMessage.subscribe(message =>
this.message = message)
}
}
about.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from
'src/app/shared/services/data.service';
@Component({
selector: 'app-about',
template: `
{{ message }}
<button (click)="newMessage()">New message</button>
`,
styleUrls: ['./sibling.component.css']
})
export class AboutComponent implements OnInit{
message: string;
constructor(private dataService: DataService){}
ngOnInit(){
this.dataService.currentMessage.subscribe(message =>
this.message = message)
}
newMessage(){
this.dataService.changeMessage('Hello from the About
component!')
}
}