简体   繁体   English

如何使用 RxJs 获取 Angular 表单控件的当前初始值

[英]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));

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取 RxJS Subject 或 Observable 的当前值? - How to get current value of RxJS Subject or Observable? Angular Reactuve 表单控件 valueChanges 获取值更改的字段名称、上一个值和当前值 - Angular Reactuve Form Control valueChanges get value changed field name , prev value and current value RxJS:如何不订阅初始值和/或未定义? - RxJS: How to not subscribe to initial value and/or undefined? 如何从不是初始值的无限 RxJs stream 中获取单个最新值? - How can I get the single latest value from an infinite RxJs stream that is not the initial value? 使用javascript获取初始表单值 - Get initial form value with javascript 如何使用从回调函数获得的值以角度设置反应形式控件的值? - How to set value in a reactive form control in angular, using the value obtained from the call back function? 如何从 Observable Angular 中获取初始值 8+ - How get initial value from an Observable Angular 8+ 你如何使用角度javascript获得表单的价值? - How do you get value of form using angular javascript? 如何获取表单输入,使用Angular Binding选择值? - How to get form input, select value using Angular Binding? 如何从Form控件中获取值以在Angular2的Javascript中使用 - How do I get the value from my Form control to use in Javascript in Angular2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM