2016-08-04 48 views
1

變化我有兩個組成部分,一個父母和孩子:使用觀測量傳播在角2

// Parent Directive 
@Component({ 
    selector: 'parent-directive', 
    template: ` 
    <button (click)="nextVal($event)"></button> 
    <button (click)="prevVal($event)"></button> 
    <child-directive [content]="myValue"></child-directive>`, 
    directives: [ChildDirective] 
}) 
export class ParentDirective { 
    public myValue : string; 

    constructor() {this.myValue = "Hello";} 

    nextVal() {this.myValue = "Next";} 

    prevVal() {this.myValue = "Prev";} 
} 

這是孩子的指令:

// Child directive 
type ObservableContent = Observable<string>; 

@Component({ 
    selector: 'child-directive', 
    template: `<div></div>` 
}) 
export class ChildDirective { 
    @Input() content : ObservableContent; 
    subscription : Subscription; 

    constructor() { 
     // I instantiate the content property as an observer. I want to see if it logs anything. 
     this.content = new Observable<string>(ob => {console.log('constructor', ob)}); 

     // I'm trying to get the propagated values here. 
     this.subscription = this.content.subscribe(value => { console.log('value', value);}); 
    } 
} 

讓我打破我是什麼試圖在這裏做。我有一個嵌套在父組件中的子組件。父級有兩個按鈕,nextprev,單擊時會更改綁定到父級範圍的屬性。

孩子有另一個屬性,content綁定到父級的myValue作用域屬性。當我在父母更新myValue時,我希望孩子的content屬性發生變化。但是,當我嘗試訂閱該值時,訂閱偵聽器永遠不會被調用。我究竟做錯了什麼?

回答

-1

正如我所見content是一個字符串,而不是一個Observable。所以你不需要在這裏使用.subscribe,因爲它會拋出一個錯誤。

在你的孩子組件this.content將永遠給你最新的價值。只需使用changeDetection: ChangeDetectionStrategy.OnPush即可。這確保角度只有在其中一個輸入屬性被更改時才更新組件。

要獲取組件中的最新值content,請使用由angular提供的ngOnChanges生命週期方法。

// Child directive 
type ObservableContent = Observable<string>; 

@Component({ 
    selector: 'child-directive', 
    template: `<div>{{content}}</div>`, 
    changeDetection: ChangeDetectionStrategy.OnPush 
}) 
export class ChildDirective { 
    @Input() content : ObservableContent; 

    ngOnChanges(changes) { 
    console.log('new content' + changes.content.currentValue); 
    console.log('old content' + changes.content.previousValue); 
    } 
} 

由於Angular的變化檢測,模板中的內容將始終反映更新的值。

+0

我認爲我們正在尋找捕捉「內容」值發生變化的時刻,但不僅僅是將其輸出到模板中。爲了在模板中輸出,你不需要任何'Observable'事物。 –

+0

我不需要將'content'值寫入模板。我需要捕獲它作爲「子」組件的屬性。 – dopatraman

+0

@AndreiZhytkevich我已經更新了答案:) – ritz078