Sibling components do not have access to each other's properties and methods. This article explores a straightforward mechanism for communication between sibling components in Angular 2, utilizing a shared service.
1. Shared Service:
Create a shared service to act as a communication hub.
@Injectable() export class SharedService { dataArray: string[] = []; insertData(data: string) { this.dataArray.unshift(data); } }
2. Parent Component:
Import and provide the shared service in the parent component.
import {SharedService} from './shared.service'; @Component({ selector: 'parent-component', template: `<child-component></child-component> <child-sibling-component></child-sibling-component>`, providers: [SharedService] }) export class ParentComponent { }
3. Child Components:
Inject the shared service into both sibling components:
Child Component 1:
import {SharedService} from './shared.service' @Component({ selector: 'child-component', template: `...` }) export class ChildComponent implements OnInit { data: string[] = []; constructor(private _sharedService: SharedService) { } }
Child Component 2 (Sibling):
import {SharedService} from './shared.service' @Component({ selector: 'child-sibling-component', template: `...` }) export class ChildSiblingComponent { data: string = 'Testing data'; constructor(private _sharedService: SharedService) { } }
4. Data Sharing:
The sibling component can modify the shared service's data array, which will be reflected in the other sibling component.
addData() { this._sharedService.insertData(this.data); this.data = ''; }
Notes:
The above is the detailed content of How Can I Communicate Between Sibling Components in Angular 2?. For more information, please follow other related articles on the PHP Chinese website!