[英]How to get current initial value of Angular form control using RxJs
I have a situation where I need to listen to the value of the form control from a different component.我有一种情况需要从不同的组件监听表单控件的值。 the valueChanges
does this just fine for any changes in the dropdown. valueChanges
对下拉列表中的任何更改都很好。 However I get a null
upon initialization in ngOnInit.但是我在 ngOnInit 中初始化时得到了null
。 Apparently the valueChanges does not get the initial value of the FormControl- only upon changing it.显然,valueChanges 没有获得 FormControl 的初始值 - 只有在更改它时才获得。 So how can I get both the initial value as well as any subsequent changes?那么我怎样才能同时获得初始值和任何后续变化呢?
An example which works fine for any changes, but not for getting an initial value upon load.一个适用于任何更改但不适用于在加载时获取初始值的示例。 If this form control already has some initial value in it, this code won't get it如果此表单控件中已有一些初始值,则此代码将无法获取它
this.form1.controls['name'].valueChanges.subscribe(change => {
console.log(change); // Value inside the input field as soon as it changes
});
You can use the startWith()
RXJS operator and provide the initial value of the form control.您可以使用startWith()
RXJS 运算符并提供表单控件的初始值。
this.form1.controls.name.valueChanges
.pipe(startWith(this.form1.controls.name.value))
.subscribe((v) => console.log(v));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.