Sibling Component Communication in Angular 2
When managing data flow between sibling components in Angular 2, there are several approaches to consider.
Shared Service with Dependency Injection
The recommended solution in Angular 2 RC4 is to utilize a shared service via dependency injection. Here's the implementation:
shared.service.ts:
import {Injectable} from '@angular/core'; @Injectable() export class SharedService { dataArray: string[] = []; insertData(data: string) { this.dataArray.unshift(data); } }
parent.component.ts (Parent component):
import {Component} from '@angular/core'; import {SharedService} from './shared.service'; import {ChildComponent} from './child.component'; import {ChildSiblingComponent} from './child-sibling.component'; @Component({ selector: 'parent-component', template: `<h1 >Parent</h1> <div> <child-component></child-component> <child-sibling-component></child-sibling-component> </div>`, providers: [SharedService], directives: [ChildComponent, ChildSiblingComponent], }) export class ParentComponent {}
child.component.ts (Child component):
import {Component, OnInit} from '@angular/core'; import {SharedService} from './shared.service'; @Component({ selector: 'child-component', template: `<h1 >I am a child</h1> <div> <ul *ngFor="#data in data"> <li>{{data}}</li> </ul> </div>` }) export class ChildComponent implements OnInit { data: string[] = []; constructor(private _sharedService: SharedService) { } ngOnInit(): any { this.data = this._sharedService.dataArray; } }
child-sibling.component.ts (Child sibling component):
import {Component} from 'angular2/core'; import {SharedService} from './shared.service'; @Component({ selector: 'child-sibling-component', template: ` <h1 >I am a child</h1> <input type="text" [(ngModel)]="data"/> <button (click)="addData()"></button>` }) export class ChildSiblingComponent { data: string = 'Testing data'; constructor(private _sharedService: SharedService) {} addData() { this._sharedService.insertData(this.data); this.data = ''; } }
Key Considerations:
The above is the detailed content of How to Implement Sibling Component Communication in Angular 2?. For more information, please follow other related articles on the PHP Chinese website!