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);});
}
}
让我打破我是什么试图在这里做。我有一个嵌套在父组件中的子组件。父级有两个按钮,next
和prev
,单击时会更改绑定到父级范围的属性。
孩子有另一个属性,content
绑定到父级的myValue
作用域属性。当我在父母更新myValue
时,我希望孩子的content
属性发生变化。但是,当我尝试订阅该值时,订阅侦听器永远不会被调用。我究竟做错了什么?
我认为我们正在寻找捕捉“内容”值发生变化的时刻,但不仅仅是将其输出到模板中。为了在模板中输出,你不需要任何'Observable'事物。 –
我不需要将'content'值写入模板。我需要捕获它作为“子”组件的属性。 – dopatraman
@AndreiZhytkevich我已经更新了答案:) – ritz078