如何实现angular中的响应式表单

发布时间:2022-01-13 09:52:52 作者:小新
来源:亿速云 阅读:132

小编给大家分享一下如何实现angular中的响应式表单,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

响应式表单

Angular 提供了两种不同的方法来通过表单处理用户输入:响应式表单模板驱动表单。【相关教程推荐:《angular教程》】

这里只介绍响应式表单,模板驱动表单请参考官网—https://angular.cn/guide/forms-overview#setup-in-template-driven-forms

全局注册响应式表单模块 ReactiveFormsModule

要使用响应式表单控件,就要从 @angular/forms 包中导入 ReactiveFormsModule,并把它添加到你的 NgModuleimports数组中。如下:app.module.ts

/***** app.module.ts *****/
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // other imports ...
    ReactiveFormsModule
  ],
})
export class AppModule { }

添加基础表单控件 FormControl

使用表单控件有三个步骤。

要注册一个表单控件,就要导入FormControl类并创建一个 FormControl的新实例,将其保存为类的属性。如下:test.component.ts

/***** test.component.ts *****/
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-name-editor',
  templateUrl: './name-editor.component.html',
  styleUrls: ['./name-editor.component.css']
})
export class TestComponent {
	// 可以在 FormControl 的构造函数设置初始值,这个例子中它是空字符串
  name = new FormControl('');
}

然后在模板中注册该控件,如下:test.component.html

<!-- test.component.html -->
<label>
  Name: <input type="text" [formControl]="name">
</label>
<!-- input 中输入的值变化的话,这里显示的值也会跟着变化 -->
<p>name: {{ name.value }}</p>

FormControl 的其它属性和方法,参阅 API 参考手册:

https://angular.cn/api/forms/FormControl#formcontrol

把表单控件分组 FormGroup

就像FormControl 的实例能让你控制单个输入框所对应的控件一样,FormGroup 的实例也能跟踪一组 FormControl 实例(比如一个表单)的表单状态。当创建 FormGroup 时,其中的每个控件都会根据其名字进行跟踪。

看下例演示:test.component.tstest.component.html

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

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
    constructor() {}

    profileForm = new FormGroup({
      firstName: new FormControl('', [Validators.required,Validators.pattern('[a-zA-Z0-9]*')]),
      lastName: new FormControl('', Validators.required),
    });
	
	onSubmit() {
		// 查看控件组各字段的值
      console.log(this.profileForm.value)
    }
}
<!-- profileForm 这个 FormGroup 通过 FormGroup 指令绑定到了 form 元素,在该模型和表单中的输入框之间创建了一个通讯层 -->
<!-- FormGroup 指令还会监听 form 元素发出的 submit 事件,并发出一个 ngSubmit 事件,让你可以绑定一个回调函数。 -->
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
    <label>
<!-- 由 FormControlName 指令把每个输入框和 FormGroup 中定义的表单控件 FormControl 绑定起来。这些表单控件会和相应的元素通讯 -->
      First Name: <input type="text" formControlName="firstName">
    </label>
    <label>
      Last Name: <input type="text" formControlName="lastName">
    </label>
    <button type="submit" [disabled]="!profileForm.valid">Submit</button>
  </form>

  <p>{{ profileForm.value }}</p>
  <!-- 控件组的状态: INVALID 或 VALID -->
  <p>{{ profileForm.status }}</p>	
  <!-- 控件组输入的值是否为有效值: true 或 false-->
  <p>{{ profileForm.valid }}</p>
  <!-- 是否禁用: true 或 false-->
  <p>{{ profileForm.disabled }}</p>

FormGroup 的其它属性和方法,参阅 API 参考手册:

https://angular.cn/api/forms/FormGroup#formgroup

使用更简单的 FormBuilder 服务生成控件实例

在响应式表单中,当需要与多个表单打交道时,手动创建多个表单控件实例会非常繁琐。FormBuilder服务提供了一些便捷方法来生成表单控件。FormBuilder在幕后也使用同样的方式来创建和返回这些实例,只是用起来更简单。

FormBuilder 是一个可注入的服务提供者,它是由 ReactiveFormModule 提供的。只要把它添加到组件的构造函数中就可以注入这个依赖。

FormBuilder服务有三个方法:control()group()array()。这些方法都是工厂方法,用于在组件类中分别生成FormControlFormGroupFormArray

看下例演示:test.component.ts

import { Component } from '@angular/core';
// 1、导入 FormBuilder
import { FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent {
	// 2、注入 FormBuilder 服务
    constructor(private fb: FormBuilder) { }
    ngOnInit() { }

    profileForm = this.fb.group({
      firstName: ['', [Validators.required, Validators.pattern('[a-zA-Z0-9]*')]],
      lastName: ['', Validators.required],
    });
    // 相当于
    // profileForm = new FormGroup({
    //   firstName: new FormControl('', [Validators.required,Validators.pattern('[a-zA-Z0-9]*')]),
    //   lastName: new FormControl('', Validators.required),
    // });

    onSubmit() {
      console.log(this.profileForm.value)
      console.log(this.profileForm)
    }
}

对比可以发现,使用FormBuilder服务可以更方便地生成FormControlFormGroupFormArray,而不必每次都手动new一个新的实例出来。

表单验证器 Validators

Validators类验证器的完整API列表,参考API手册:

https://angular.cn/api/forms/Validators

验证器(Validators)函数可以是同步函数,也可以是异步函数。

出于性能方面的考虑,只有在所有同步验证器都通过之后,Angular 才会运行异步验证器。当每一个异步验证器都执行完之后,才会设置这些验证错误。

验证器Validators类的API

https://angular.cn/api/forms/Validators

class Validators {
  static min(min: number): ValidatorFn		// 允许输入的最小数值
  static max(max: number): ValidatorFn		// 最大数值
  static required(control: AbstractControl): ValidationErrors | null	// 是否必填
  static requiredTrue(control: AbstractControl): ValidationErrors | null
  static email(control: AbstractControl): ValidationErrors | null	// 是否为邮箱格式
  static minLength(minLength: number): ValidatorFn		// 最小长度
  static maxLength(maxLength: number): ValidatorFn		// 最大长度
  static pattern(pattern: string | RegExp): ValidatorFn	// 正则匹配
  static nullValidator(control: AbstractControl): ValidationErrors | null	// 什么也不做
  static compose(validators: ValidatorFn[]): ValidatorFn | null
  static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn | null
}

内置验证器函数

要使用内置验证器,可以在实例化FormControl控件的时候添加

import { Validators } from '@angular/forms';
...
ngOnInit(): void {
  this.heroForm = new FormGroup({
  // 实例化 FormControl 控件
    name: new FormControl(this.hero.name, [
      Validators.required,	// 验证,必填
      Validators.minLength(4),	// 长度不小于4
      forbiddenNameValidator(/bob/i) // 自定义验证器
    ]),
    alterEgo: new FormControl(this.hero.alterEgo),
    power: new FormControl(this.hero.power, Validators.required)
  });
}
get name() { return this.heroForm.get('name'); }

get power() { return this.heroForm.get('power'); }

自定义验证器

自定义验证器的内容请参考 API手册:

https://angular.cn/guide/form-validation

有时候内置的验证器并不能很好的满足需求,比如,我们需要对一个表单进行验证,要求输入的值只能为某一个数组中的值,而这个数组中的值是随程序运行实时改变的,这个时候内置的验证器就无法满足这个需求,需要创建自定义验证器。

以上是“如何实现angular中的响应式表单”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. Angular8如何实现表单及其验证
  2. angular中两种表单的区别(响应式和模板驱动表单)

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

angular

上一篇:linux中x64和x86有哪些区别

下一篇:PHP_CodeSniffer怎么安装使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》