2017-01-09 61 views
0

我想將數據發送到不是子組件或父組件的另一個組件。Angular 2在不相關的組件之間發送對象

我創建了一個Plunker來顯示我所要求的。

當下面的代碼被激發時我想聽點什麼。

fillSelectT(item){ 
    //populate Select to 
} 

以下代碼應該監聽數據。

listener(item){ 
    selectedItems.push(item); 
    } 

在C#這將是simmular到EventAggregator什麼,我試圖找出。

回答

2

作爲documented here:你應該在兩個部件之間共享服務,發射從服務事件選擇一個項目時,並收聽來自其它部件發出的事件。

@Injectable() 
class SelectionService { 
    selections = new Subject<any> 
    select(item) { 
    this.selections.next(item); 
    } 
} 

你plunkr,修改:http://plnkr.co/edit/qJ8bh7wN9qQvKTLJOb0T?p=preview

0

我做了充分的工作例證,基於你的。

1)兩種組分的AppComponent子,然後創建變量和事件來觸發並存儲那些:

selectedItems: any[] = []; 

onSelectItem(item) { 
    this.selectedItems.push(item); 
} 

<select-from (onSelectItem)="onSelectItem($event)"></select-from> 
<select-to [selectedItems]="selectedItems"></select-to> 

2)修改select-from組件觸發事件:

@Output() onSelectItem = new EventEmitter<any>(); 

fillSelectT(item){ 
     this.onSelectItem.emit(item); 
} 

3 )修改select-to組件以從其來電組件接收列表:

@Input() selectedItems:any = []; 

在這裏,修改:Plunker

相關問題