Angular react 形式 : valueChanges doesn't work as expected

标签 angular typescript angular6 angular-reactive-forms

我正在学习在 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/

相关文章:

Angular6 Material6 错误 : "There can only be one default row without a when predicate function."

angular - 使用静态数组作为 mat-table 的数据源

javascript - 获取 Angular 4 中随机数的单元测试

typescript - 我可以使用 Nestjs 注入(inject)接口(interface)而不是类吗?

angular - 根据用户选择顺序保存多个选择的 ngModel 绑定(bind)值

Angular 6 错误 : CSSSyntaxError - Failed to compile

angular - 如何使用 canActivate 保护 Angular CLI Assets

Angular Material 5 深色主题未应用于 body

reactjs - 类型中缺少不应手动传递给子组件的属性

java - 如何使用云功能使用 firestore 中的文档名称填充应用程序中的微调器?