-1

I am practicing template-driven forms in Angular. Below is the example of this simple form.

import { NgForm } from "@angular/forms";

onSubmit(form: NgForm): void {
  console.log(form.value);
}
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
  Username:
  <input type="text" name="user_name" ngModel/>
  Password:
  <input type="password" name="password" ngModel/>
  <button type="submit">Submit</button>
</form>

The default way of logging to the console is like the following,

password: "123456" user_name: "shah"

But I want the keys should be shown according to the order in the form, like this,

user_name: "shah" password: "123456"

Is there any way to do this?

Shah Shishir
  • 161
  • 2
  • 4
  • 13
  • 1
    Does this answer your question? [How to prevent automatic sort of Object numeric property?](https://stackoverflow.com/questions/33351816/how-to-prevent-automatic-sort-of-object-numeric-property) – R. Richards Nov 22 '20 at 15:50

1 Answers1

1

Object in Javascript doesn't have an order.

You can use a FormArray, which internally has sort functionality.

Or if you really wany to do it with object, you probably have to store your controls inside an array and change the order

Oleksii Pavlenko
  • 1,327
  • 1
  • 11
  • 25