2016-09-28 47 views
0

我試圖綁定一個動態組件的var,但是當這個var在父級更改時,這些更改並未到達子組件,因爲它發生在我們將var綁定到固定組件時的情況,如下所示:Angular 2:是否可以綁定動態組件中的var?

<child-component [myVar]="myVar"><child-component> 

我試圖使用屬性實例如下做到這一點,但它不能正常工作,它只是傳遞的原始值,但不會改變:

this.componentRef.instance.myVar = this.myVar; 

我已經創建了一個Plunker例如,Example in Plunker

+0

您還必須通過更改。您可以傳遞動態組件可以訂閱的觀察值,以獲取有關更改的通知。 –

+0

如果你可以解決手動更新問題,那麼把'this.componentRef.instance.selection = this.selection;'放在'changeSelection'方法的末尾。 – lbrahim

+0

謝謝@Ibrahim,在這個例子中它可以工作,但有時var其他組件的變化,所以我不能這樣做。 – ChristianGH

回答

0

也許你可以從觀察到的&使流然後訂閱它在你的組件,因此每次它改變了你的組件將更新相應的值:在你的根級別注入該服務後

import { Injectable } from '@angular/core'; 
import {Subject} from 'rxjs/Subject'; 
@Injectable() 
export class ViewToggleService { 
    leftVisible:boolean=true; 
    // Observable boolean source 
    private leftVisibleSource = new Subject<boolean>(); 
    // Observable boolean stream 
    leftVisibleStream$=this.leftVisibleSource.asObservable(); 
    constructor(){ 
    } 
    // service command 
    toggleView(viewName:string){  
     if(viewName.toString()==='leftVisible'){ 
     this.leftVisible=!this.leftVisible; 
     this.leftVisibleSource.next(this.leftVisible); 
     } 
    } 
} 

然後,在你的組件內,你可以訂閱這個流如下:

public leftVisible: boolean; 
subscriptionLeftVisible: Subscription; 
ngOnInit() {  
    this.subscriptionLeftVisible = this._viewToggleService.leftVisibleStream$.subscribe(leftVisible => { 
     this.leftVisible = leftVisible; 
    }); 
} 

希望這會有所幫助。

相關問題