In the app.module.ts
, in the imports section, declare the class ReactiveFormsModule:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ReactiveFormsModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Component } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
genders = ['male', 'female'];
signupForm : FormGroup;
}
And initialize it:
ngOnInit() {
this.signupForm = new FormGroup( {
"username": new FormControl( null ),
"email" : new FormControl( null ),
"gender" : new FormControl( 'male' )
} );
}
And link it with the real form in the template:
<form [formGroup]="signupForm">
And link everyone of the controls of the form of the template with the form controls:
<input
type="text"
id="email"
formControlName="email"
class="form-control">
Validators can be added in the second parameter of the creation. For instance, Validators.required
adds a validator
that requires that this field is required:
"username": new FormControl( null, Validators.required ),
"email" : new FormControl( null, [Validators.required,
Validators.email ] ),