响应式表单验证示例

1、在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文件

<form [formGroup]="fg">
    <label for="username">用户名:</label>                           
    <input type="text" id="username" formControlName="username" required>
    
     <!-- 这里的username关联的是从后台FormGroup里取出的FormControl对象 -->
    <div *ngIf= "username.invalid && (username.dirty||username.touched)">
        <div *ngIf="username.errors.required">
            用户名是必填项
        </div>
        <div *ngIf="username.errors.minlength">
            用户名最小长度是5
        </div>
    </div>
</form>
3、ts文件
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)]),
    });
  }
   //返回FormGroup里的FormControl对象
  get username(){
    return this.fg.get('username');
  }
}
 

猜你喜欢

转载自www.cnblogs.com/kukai/p/12113018.html