user12727701
user12727701

Reputation: 13

Angular 8 app unable to retrieve form field value when using router.navigate

I have an Angular 8 app that uses routing and template driven forms.

I have a simple form in component.html:

<form (ngSubmit)="onSubmit(serviceForm)" #serviceForm="ngForm">
  <input type="text" name="endpoint" ngModel>
  <button class="btn btn-success" type="submit">Submit</button>
</form>

A handler in component.ts:

onSubmit(serviceForm:NgForm){
  console.log(serviceForm);
  this.router.navigate(['/view-service']);
 }

"Endpoint" isn't available in ngForm.value when I call the navigate statement after console.log(). Here is an output from console.log:

NgForm {submitted: true, _directives: Array(1), ngSubmit: EventEmitter, form: FormGroup}
formDirective: (...)
control: (...)
path: (...)
controls: (...)
value: Object
__proto__: Object

valid: (...)
invalid: (...)
pending: (...)
disabled: (...)
enabled: (...)
errors: (...)
pristine: (...)
dirty: true
touched: true
status: (...)
untouched: (...)
statusChanges: (...)
valueChanges: (...)
submitted: true

If I don't call the navigate statement, it is available.

I don't get it, I print out to console before I navigate.

What am I doing wrong here?

Thanks!

Upvotes: 1

Views: 890

Answers (1)

Dean
Dean

Reputation: 2273

This is because you are looking at the form but what you want is a specific value contained in the form. Change your code to the following:

onSubmit(serviceForm: NgForm){
  console.log(serviceForm.value.endpoint);
}

I created a demo app on stackblitz that illustrates this using your exact form. Also - be sure to read the docs on forms.

Edit to address your edited question

You are logging a reference to your form object, but by the time you inspect it in the dev tools, you have navigated away from the page, and the form values are thus not available. This is explained in the MDN Web Docs. Specifically:

Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you open the console.

Give the MDN suggestion a try:

Logging objects

Don't use console.log(obj), use console.log(JSON.parse(JSON.stringify(obj))).

Upvotes: 2

Related Questions