1, the configuration file in APPModule.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { ReactiveFormComponent } from './reactive-form/reactive-form.component';
@NgModule ({
declarations: [
AppComponent,
ReactiveFormComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
2, html file
<form [formGroup]="fg">
<label for="username">用户名:</label>
<input type="text" id="username" formControlName="username" required>
<! - username associated with the object here is taken from the back FormControl FormGroup lining ->
<div *ngIf=
"username.invalid && (username.dirty||username.touched)">
<div *ngIf="username.errors.required">
User name is required
</div>
<div *ngIf="username.errors.minlength">
Username minimum length 5
</div>
</div>
</form>
3, ts files
import { Component, OnInit } from '@angular/core';
import { FormControl ,FormGroup,Validators} from '@angular/forms';
@Component({
selector: 'app-reactive-form',
templateUrl: './reactive-form.component.html'
styleUrls: ['./reactive-form.component.css']
})
export class ReactiveFormComponent implements OnInit {
public fg:FormGroup;
constructor() { }
ngOnInit () {
this.validatorGroup();
}
validatorGroup () {
this.fg=new FormGroup({
username:new FormControl('',[Validators.required,Validators.minLength(5)]),
});
}
// returns FormGroup objects in the FormControl
get username(){
return this.fg.get('username');
}
}