If I have the following:
<form
id="registration"
name="registration"
method="POST"
>
<input
type="text"
name="first_name"
id="first-name"
ng-model="registration.first_name"
placeholder="First name"
/>
When my form displays, fields configured as above end up having [Object object]
inside of them for their initial value.
What am I doing wrong here and what's the correct way to get two-way binding inside of a form?
The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.
The ngmodel directive is not part of the Angular Core library. It is part of the FormsModule library. You need to import the FormsModule package into your Angular module. If you want to create a form in angular app then you need to import FormsModule from @angular/forms library.
name: An alternative to setting the name attribute on the form control element. See the example for using NgModel as a standalone control. standalone: When set to true, the ngModel will not register itself with its parent form, and acts as if it's not in the form.
Setting the name
attribute on a form creates a scope object which is useful for validation but is not meant to be used for the ng-model
attributes of inputs.
If you use a separate scope variable for ng-model, it will work as you expect:
<form
...
name="reg"
...
>
<input
...
ng-model="registration.first_name"
...
/>
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With