1

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!

0

1 Answer 1

2

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))).

Sign up to request clarification or add additional context in comments.

3 Comments

Dean - Look at the bold text above....endpoint is not in the value key because I am routing immediately after...THat's the issue, serviceForm.value.endpoint is only available if I don't call the routing statement after console.log, and I want to be able to route...
It's a misunderstanding about what exactly console.log is doing. I edited my answer to address your edited question.
That did it. Appreciate the assist Dean!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.