import FormsModule
import { FormsModule } from '@angular/forms';
@NgModule ({
...
imports: [
FormsModule,
...
]
})
Add Form and submit handling HTML Template:
<form #myForm="ngForm"
(submit)="handleSubmit(myForm.value)"
>
<button type="submit">Submit</button>
</form>
Component:
public handleSubmit(formValue: any) {
console.log(formValue);
}
Add Fields
<div>
<label for="usernameInput">Username</label>
<input type="text"
id="usernameInput"
name="username"
ngModel
placeholder="enter username"
>
</div>
Available form properties
myForm.errors
myForm.dirty
myForm.valid
-
NgForm
automatically binds to a<form>
element and creates aFormGroup
object calledngForm
. With#myForm="ngForm"
we actually grab this FormGroup object and bind it to a template variable. -
NgForm
automatically creates the(submit)
event emitter. -
NgModel
directive creates automatically aFormControl
named with thename
value. -
NgModel
creates a one-way data bind (model -> view)