1) @Input
Az adatkötéssel a szülő komponens átadhat adatokat a gyermek komponensnek a @Input dekorátorral.
2) @Output / EventEmitter
@Output és EventEmitter használatával.és a gyermek komponens visszatérthet adatokkal.
3) Service
A servicek segítségével központosított kommunikációt valósíthatunk meg a komponensek között. A komponensek injektálhatják a serviceket, és ezáltal közös adatokat és üzleti logikát használhatnak.
4) ViewChild
A ViewChild egy dekorátor, amely segítségével hivatkozást kaphatunk egy gyermek komponensre, direktívára vagy DOM elemre a szülő komponensben.
@Input – Parent to Child
Parent
export class InputParentToChildComponent {
message = 'Hello from Parent Component!';
}
<app-input-child [message]="message"></app-input-child>
Child
export class InputChildComponent {
@Input() message?: string;
}
<p>{{ message }}</p>
@Output / EventEmitter – Child to Parent
Child
export class OutputChildClickComponent {
message?: string = 'Hello from Child Component';
@Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit(this.message);
}
}
<button (click)="sendMessage()">Send Message</button>
Parent
export class OutputChildToParentClickComponent {
message?: string;
receiveMessage($event: string | undefined) {
this.message = $event;
}
}
<app-child
(messageEvent)="receiveMessage($event)"
></app-child>
3) Service
Data Service
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class DataService {
private messageSource = new BehaviorSubject('');
currentMessage = this.messageSource.asObservable();
constructor() {}
changeMessage(message: string) {
this.messageSource.next(message);
}
}
Parent
export class ParentComponent implements OnInit, OnDestroy {
message?: string;
subscription?: Subscription;
constructor(private data: DataService) {}
ngOnInit() {
this.subscription = this.data.currentMessage.subscribe(
(message) => (this.message = message)
);
}
ngOnDestroy() {
this.subscription?.unsubscribe();
}
newMessage() {
this.data.changeMessage('Hello from Parent');
}
}
<button (click)="newMessage()" class="cta-blue">
Send Message to Sibling
</button>
Sibling
export class SiblingComponent implements OnInit, OnDestroy {
message?: string;
subscription?: Subscription;
constructor(private data: DataService) {}
ngOnInit() {
this.subscription = this.data.currentMessage.subscribe(
(message) => (this.message = message)
);
}
ngOnDestroy() {
this.subscription?.unsubscribe();
}
}
<p>{{ message }}</p>