2016-08-04 47 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