如何使输入可观察? [英] How can I make an input observable?
问题描述
我有一个带有一些输入的组件,希望在更改时得到通知.目前,我可以通过实现ngOnChanges
并确定更改了哪些输入来使其工作.但是,我希望将输入声明设置为@Input('select-values') selectValues:Observable<any>
.这将使我能够以更简洁的方式订阅发生的任何新更改.
I have a component with a few inputs that I'd like to be notified when it changes. I currently have it working by implementing ngOnChanges
and figuring out which input was changed. However, I would prefer set my input declaration to @Input('select-values') selectValues:Observable<any>
. This would allow me to subscribe to any new changes that occur in a much cleaner fashion.
ngOnInit() {
this.selectValues.subscribe(() => console.log('yay!'));
}
问题是我遇到异常TypeError: this.selectValues.subscribe is not a function
.
刚刚发现这也行得通– 组件交互.拦截器输入属性会随着设置器的变化而改变.
Just found out that this also works – Component Interaction. Intercept input property changes with a setter.
推荐答案
您可以将它们包装成表格并听取更改
You can wrap them in a form and listen to changes
this.myForm = fb.group({
'sku': ['', Validators.required]
});
this.sku = this.myForm.controls['sku'];
this.sku.valueChanges.subscribe(
(value: string) => {
console.log('sku changed to: ', value);
}
);
this.myForm.valueChanges.subscribe(
(value: string) => {
console.log('form changed to: ', value);
}
);
http://blog.ng -book.com/the-ultimate-guide-to-forms-in-angular-2/
或
@Component({
...,
template: '<input (change)="onChange($event.target.value)">'
})
class MyComponent {
this.inputChange =new Subject();
onChange(e) {
this.inputChange.next(e);
}
}
另请参见此问题,打开 https://github.com/angular/angular/issues/4062
See also this issue open https://github.com/angular/angular/issues/4062
这篇关于如何使输入可观察?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!