emery
emery

Reputation: 157

Angular: form control value and form value not the same

When using the valueChanges callback in Angular I noticed the values form.get('field').value and form.value.field are not the same.

Example:

this.form = this.fb.group({
  email: ['[email protected]'],
)}

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

On the first change this.form.get('email').value will equal value of value (= the updated value). But this.form.value.email will still equal [email protected].

You may also try out the stackblitz here https://stackblitz.com/edit/angular-8-reactive-form-jrvley?file=src/app/app.component.ts

Upvotes: 3

Views: 3404

Answers (1)

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

It's because you're logging from within the form control changes, and the form group probably hasn't been updated yet.

If you log the form group value from within the form group value changes observable, you see matching results.

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

I changed

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}`);
})

to

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}`);
})

Edit:

And to answer your other question, I always use the this.form.get('name') syntax. Mainly for compatibility with dynamically built forms.

Upvotes: 6

Related Questions