Angular 2 中的同級組件通訊
在Angular 2 中管理同級組件之間的資料流時,有多種方法需要考慮。
具有依賴關係的共享服務注入
Angular 2 RC4 中推薦的解決方案是透過依賴注入來利用共享服務。這是實作:
shared.service.ts:
import {Injectable} from '@angular/core'; @Injectable() export class SharedService { dataArray: string[] = []; insertData(data: string) { this.dataArray.unshift(data); } }
parent.component.ts(父組件):
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(子組件):
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(子兄弟組件):
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 = ''; } }
關鍵注意事項:
以上是如何在 Angular 2 中實作兄弟元件通訊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!