我正在学习在 Angular 6 中使用响应式表单,所以如果这个问题很愚蠢,请原谅我,但这是我的问题:
我想以我的 react 形式监视某个值的变化,因为当发生变化时,我需要运行一些逻辑来根据新值重新计算内容。所以我试过这样做:
this.inputGroup = formBuilder.group({
myControl: 'something'
});
this.inputGroup.get('myControl').valueChanges.subscribe(newVal => {
console.log("new value", newVal); //Prints the correct new value
console.log("actual value", this.inputGroup.value.myControl); //Prints the previous (old) value!
this.someFuncThatExpectsTheValuesToBeUpToDate(); //This will find the OLD value inside this.inputGroup.value.myControl, instead of the new one!
});
但是,正如您从我在代码中添加的注释所看到的,这是行不通的,因为
valueChanges
好像被叫了之前 该值实际上在模型中发生了变化!这是预期的行为吗? valueChanges
的方法签名说:A multicasting observable that emits an event every time the value of the control changes, in the UI or programmatically.
所以我会假设它是在表单中更改值后调用的,但显然不是......这是正确的吗?如果是这样,我如何检测控件中的值何时实际更改?
编辑 :关于为什么我希望我的函数直接从 Form 组访问数据,而不是将新值传递给函数本身,似乎存在一些混淆(在 SO :D 上总是如此)。这很容易解释:该函数从多个表单组收集数据,并使用这些数据进行一些辅助计算。通过直接从表单组访问数据,该函数是通用的,可以从任何地方调用。如果我开始将输入参数放在那里,这会中断。拿这个例子:
someFuncThatExpectsTheValuesToBeUpToDate(){
let val1 = inputGroup.value.myControl;
let val2 = someOtherFormGroup.value.myOtherControl;
let val3 = yetAnotherFormGroup.value.someOtherControl;
//do something with the vals
}
有了这个函数,我可以从任何地方调用它并且它会起作用。但是如果我每次都需要传递值,我需要 3 个具有不同签名的不同函数来做同样的事情,更加困惑和复杂。
最佳答案
valueChanges
在新值更新为 FormControl 值之后,并且在更改冒泡到其父级和祖先之前触发事件。因此,您必须访问 FormControl 本身的值,而不是 FormGroup 值对象的字段。
控制台日志this.inputGroup.get('myControl').value
在 subscribe 中,它将具有新值。
关于 Angular react 形式 : valueChanges doesn't work as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52837270/