In app.module.ts
I add ReactiveFormsModule
in my imports
section. Remember to import it at the top as: import { ReactiveFormsModule} from '@angular/forms
.
In your app.component.ts
you have to define FormGroup
instance and initialize/register it via ngOnInit
method as below:
import { FormGroup, FormControl } from '@angular/forms'; //imports
.......................................................................
myForm:FormGroup;
ngOnInit(){
this.myForm = new FormGroup({
'name':new FormControl(null), //note, can have up to 3 Constructor Params: default value, validators, AsyncValidators
'email':new FormControl(null,Validators.email)
})
}
Then bind form to the FormGroup
instance myForm
:
<form [formGroup]="myForm">
Note that name
and email
are controls in the form that needs binding using formControlName
:
<input type="text" name="name" formControlName="name">
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…