Home >Web Front-end >JS Tutorial >How can sibling components communicate in Angular 2?
Angular 2 Component Communication Amongst Siblings
In Angular 2, sibling component communication can be achieved through dependency injection and shared services.
Shared Service Approach (Angular 2 RC4 and Later)
The recommended approach involves creating a shared service that sibling components can access via dependency injection. Here's an example:
// shared.service.ts @Injectable() export class SharedService { dataArray: string[] = []; insertData(data: string) { this.dataArray.unshift(data); } }
Parent Component:
// parent.component.ts @Component({ providers: [SharedService], directives: [ChildComponent, ChildSiblingComponent] }) export class parentComponent { }
Sibling Components:
// child.component.ts constructor(private _sharedService: SharedService) { } ngOnInit(): void { this.data = this._sharedService.dataArray; } // child-sibling.component.ts constructor(private _sharedService: SharedService) {} addData() { this._sharedService.insertData(this.data); this.data = ''; }
Benefits of this Method:
Note:
The above is the detailed content of How can sibling components communicate in Angular 2?. For more information, please follow other related articles on the PHP Chinese website!