您好,欢迎访问代理记账网站
移动应用 微信公众号 联系我们

咨询热线 -

电话 15988168888

联系客服
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

Angular响应式表单

Angular响应式表单的控制逻辑写在组件类中,对验证逻辑有更多的控制权,适合复杂表单类型。
一、Angular响应式表单基本用法
FormGroup:表单组,表单至少是一个FormGroup
FormControl:表单组的一个表单项
1、引入ReactiveFormsModule

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TemplateFormsComponent } from './components/templateForms/templateForms.component';
import { ReativeFormsComponent } from './components/reativeForms/reativeForms.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
    TemplateFormsComponent,
    ReativeFormsComponent
  ],
  exports: [
    TemplateFormsComponent,
    ReativeFormsComponent
  ]
})
export class ThreeFormsModule { }

2、在组件类中创建FormsGroup表单控制对象

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-reativeForms',
  templateUrl: './reativeForms.component.html',
  styleUrls: ['./reativeForms.component.less']
})
export class ReativeFormsComponent implements OnInit {
  personMes: FormGroup=new FormGroup({
    name: new FormControl(),
    address: new FormControl()
  })
  constructor() { }
  ngOnInit() {
  }
  OnSubmit(){
    console.log(this.personMes.value)
  }
}

3、关联组件模板中的表单

<form [formGroup]="personMes" (submit)="OnSubmit()">
  <input type="text" formControlName="name"><br>
  <input type="text" formControlName="address"><br>
  <button>提交</button>
</form>

4、效果
在这里插入图片描述
二、Angular响应式表单分组
1、在模板中增加formGropName,在组件类中personMes表单对象new FormGroup子对象

<form [formGroup]="personMes" (submit)="OnSubmit()">
  <div formGroupName="nameList">
    <input type="text" formControlName="name"><br>
  </div>
  <input type="text" formControlName="address"><br>
  <button>提交</button>
</form>
export class ReativeFormsComponent implements OnInit {
  personMes: FormGroup=new FormGroup({
    nameList: new FormGroup({ name: new FormControl()
}),
    address: new FormControl()
  })
  constructor() { }

  ngOnInit() {
  }
  OnSubmit(){
    console.log(this.personMes.value)
    console.log(this.personMes.value.nameList.name)
  }
}

2、效果
在这里插入图片描述

三、Angular响应式表单验证
Angular响应式表单有内置验证、自定义验证。内置验证方法有,Validators.required(内容不可为空)、Validators.minLength()(内容最小长度)、Validators.maxLength()(内容最大长度)。自定义验证方法分为同步验证和异步验证,同步验证主要验证正则表达规则,异步验证主要与服务器交互,例如查询呢称是否重名。
1、内置验证

<form [formGroup]="personMes" (submit)="OnSubmit()">
  <input type="text" formControlName="name"><br>
  <ng-container *ngIf="name?.touched&&name?.invalid&&name?.errors">
  <div *ngIf="name?.errors?.required">内容不能为空</div>
  <div *ngIf="name?.errors?.minlength">长度不可小于2</div>
  </ng-container>
  <input type="text" formControlName="address"><br>
  <button>提交</button>
</form>
export class ReativeFormsComponent implements OnInit {
  personMes: FormGroup=new FormGroup({
    name: new FormControl("",[Validators.required,Validators.minLength(2)]),
    address: new FormControl()
  })
  get name() {
    return this.personMes.get("name")
  }
  constructor() { }

  ngOnInit() {
  }
  OnSubmit(){
    console.log(this.personMes.value)
  }
}

效果:
在这里插入图片描述
在这里插入图片描述
2、同步类型自定义验证
创建自定义验证器,class myValidators,内部自定义方法必须是静态方法。

<form [formGroup]="personMes" (submit)="OnSubmit()">
  <input type="text" formControlName="name"><br>
  <ng-container *ngIf="name?.touched&&name?.invalid&&name?.errors">
  <div *ngIf="name?.errors?.required">内容不能为空</div>
  <div *ngIf="name?.errors?.minlength">长度不可小于2</div>
  <div *ngIf="name?.errors?.isENG">必须为大写字母</div>
  </ng-container>
  <input type="text" formControlName="address"><br>
  <button>提交</button>
</form>
import { AbstractControl } from "@angular/forms";
//自定义验证规则
export class myValidators {
   static isENG(formControl: AbstractControl){
       if(/[A-Z]+/.test(formControl.value)){
           return { isENG: false}
       }else{
           return { isENG: true }
       }
   }
}
export class ReativeFormsComponent implements OnInit {
  personMes: FormGroup=new FormGroup({
    name: new FormControl("",[Validators.required,Validators.minLength(2),myValidators.isENG]),
    address: new FormControl()
  })
  get name() {
    return this.personMes.get("name")
  }
  constructor() { }

  ngOnInit() {
  }
  OnSubmit(){
    console.log(this.personMes.value)
  }
}

效果
在这里插入图片描述
3、异步类型自定义验证
在创建自定义验证器class myValidators中新创建静态方法isUnique,方法的返回值一定要是Promise或Obserable或null,在name: new FormControl中注册异步验证,在html中name?.errors?.isUnique判断值是否为true,为true则显示用户名已存在,否则通过验证。

<form [formGroup]="personMes" (submit)="OnSubmit()">
  <input type="text" formControlName="name"><br>
  <ng-container *ngIf="name?.touched&&name?.invalid&&name?.errors">
    <div *ngIf="name?.errors?.required">内容不能为空</div>
    <div *ngIf="name?.errors?.minlength">长度不可小于2</div>
    <div *ngIf="name?.errors?.isENG">必须为大写字母</div>
    <div *ngIf="name?.errors?.isUnique">用户名已存在</div>
  </ng-container>
  <div *ngIf="name?.pending">验证中...</div>
  <input type="text" formControlName="address"><br>
  <button>提交</button>
</form>
export class ReativeFormsComponent implements OnInit {
  personMes: FormGroup=new FormGroup({
    name: new FormControl(
      "", [Validators.required, Validators.minLength(2), myValidators.isENG], myValidators.isUnique
        // asyncValidators: [this.myValidatorst.validate.bind(this.myValidatorst)]
      ),
    address: new FormControl()
  }, )
  get name() {
    return this.personMes.get("name")
  }
  constructor(private myValidatorst: myValidatorsT ) { }

  ngOnInit() {
  }
  OnSubmit(){
    console.log(this.personMes.value)
    console.log(this.name)
  }
}
static isUnique(formControl: AbstractControl):Promise<ValidationErrors> {
       return new Promise(function(resolve){
           setTimeout(function(){
               if(formControl.value=="ADM"){
                    resolve({isUnique: true})
               }else{
                    resolve({ isUnique: false })
               }
           },2000)
       })
    }

效果
在这里插入图片描述
在这里插入图片描述
四、创建Angular响应式表单的快捷方式——FormBuilder
在constructor中注入FormBuilder服务,简化操作,无需new FormGroup和new FormControl

export class ReativeFormsComponent implements OnInit {
  personMes!: FormGroup;
  get name() {
    return this.personMes.get("name")
  }
  constructor(private fb: FormBuilder) {
    this.personMes =this.fb.group({
      name: [
        "", [Validators.required, Validators.minLength(2), myValidators.isENG], myValidators.isUnique
        // asyncValidators: [this.myValidatorst.validate.bind(this.myValidatorst)]
      ],
      address: [""]
    })
  }

  ngOnInit() {
  }
  OnSubmit(){
    console.log(this.personMes.value)
    console.log(this.name)
  }
}

效果和上一例一样


分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进