【问题标题】:Angular: form control value and form value not the sameAngular:表单控制值和表单值不一样
【发布时间】:2020-02-14 15:09:55
【问题描述】:

在 Angular 中使用 valueChanges 回调时,我注意到 form.get('field').valueform.value.field 的值不一样。

例子:

this.form = this.fb.group({
  email: ['default@example.com'],
)}

this.form.get('email').valueChanges.subscribe(value => {
  console.log(this.form.get('email').value);
  console.log(this.form.value.email);
});

在第一次更改时,this.form.get('email').value 将等于 value 的值(= 更新后的值)。但this.form.value.email 仍将等于default@example.com

  • 这是预期的行为吗?
  • 我是否应该始终使用 this.form.get('email').value 而不是 this.form.value.email

你也可以在这里https://stackblitz.com/edit/angular-8-reactive-form-jrvley?file=src/app/app.component.ts试试stackblitz

【问题讨论】:

  • 好问题,如果您订阅 form.valueChanges 值始终相同,请注意

标签: angular


【解决方案1】:

这是因为您正在从表单控件更改中记录,而表单组可能尚未更新。

如果您从可观察到的表单组值更改中记录表单组值,您会看到匹配的结果。

https://stackblitz.com/edit/angular-8-reactive-form-fg8hws

我变了

this.contactForm.get('email').valueChanges.subscribe(value => {
  console.log(`VALUE: ${value}`);
  console.log(`FORM CONTROL VALUE: ${this.contactForm.get('email').value}`);
  console.log(`FORM VALUE: ${this.contactForm.value.email}`);
})

this.contactForm.get('email').valueChanges.subscribe(value => {
  console.log(`VALUE: ${value}`);
  console.log(`FORM CONTROL VALUE: ${this.contactForm.get('email').value}`);      
})

this.contactForm.valueChanges.subscribe(value => {
  console.log(`FORM VALUE: ${this.contactForm.value.email}`);
})

编辑:

为了回答您的其他问题,我总是使用 this.form.get('name') 语法。主要是为了与动态构建的表单兼容。

【讨论】:

    猜你喜欢
    • 2010-10-12
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多