本篇文章带大家了解一下angular中的表单,了解一下两种类型的表单:模板驱动和模型驱动,希望对大家有所帮助!
在 angular 中,表单有两种类型,分别为模板驱动和模型驱动。【相关教程推荐:《angular教程》】
一、模板驱动1.1 概述
表单的控制逻辑写在组件模板中,适合简单的表单类型。
1.2 快速上手
1)、引入依赖模块 formsmodule
import { formsmodule } from "@angular/forms"@ngmodule({ imports: [formsmodule],})export class appmodule {}
2)、将 dom 表单转换为 ngform
<form #f="ngform" (submit)="onsubmit(f)"></form>
3)、声明表单字段为 ngmodel
<form #f="ngform" (submit)="onsubmit(f)"> <input type="text" name="username" ngmodel /> <button>提交</button></form>
4)、获取表单字段值
import { ngform } from "@angular/forms"export class appcomponent { onsubmit(form: ngform) { console.log(form.value) // {username: ''} }}
5)、表单分组
<form #f="ngform" (submit)="onsubmit(f)"> <div ngmodelgroup="user"> <input type="text" name="username" ngmodel /> </div> <div ngmodelgroup="contact"> <input type="text" name="phone" ngmodel /> </div> <button>提交</button></form>
import { ngform } from "@angular/forms"export class appcomponent { onsubmit(form: ngform) { console.log(form.value) // {contact: {phone: ''}, user:{username: ''}} }}
1.3 表单验证
required 必填字段minlength 字段最小长度maxlength 字段最大长度pattern 验证正则 例如:pattern=“\d” 匹配一个数值<form #f="ngform" (submit)="onsubmit(f)"> <input type="text" name="username" ngmodel required pattern="\d" /> <button>提交</button></form>
export class appcomponent { onsubmit(form: ngform) { // 查看表单整体是否验证通过 console.log(form.valid) }}
<!-- 表单整体未通过验证时禁用提交表单 --><button type="submit" [disabled]="f.invalid">提交</button>
在组件模板中显示表单项未通过时的错误信息。
<form #f="ngform" (submit)="onsubmit(f)"> <input #username="ngmodel" /> <div *ngif="username.touched && !username.valid && username.errors"> <div *ngif="username.errors.required">请填写用户名</div> <div *ngif="username.errors.pattern">不符合正则规则</div> </div></form>
指定表单项未通过验证时的样式。
input.ng-touched.ng-invalid { border: 2px solid red;}
二、模型驱动
2.1 概述
表单的控制逻辑写在组件类中,对验证逻辑拥有更多的控制权,适合复杂的表单的类型。
在模型驱动表单中,表单字段需要是 formcontrol类的实例,实例对象可以验证表单字段中的值,值是否被修改过等等
一组表单字段构成整个表单,整个表单需要是 formgroup 类的实例,它可以对表单进行整体验证。
formcontrol:表单组中的一个表单项
formgroup:表单组,表单至少是一个 formgroup
formarray:用于复杂表单,可以动态添加表单项或表单组,在表单验证时,formarray 中有一项没通过,整体没通过。
2.2 快速上手
1)、引入 reactiveformsmodule
import { reactiveformsmodule } from "@angular/forms"@ngmodule({ imports: [reactiveformsmodule]})export class appmodule {}
2)、在组件类中创建 formgroup 表单控制对象
import { formcontrol, formgroup } from "@angular/forms"export class appcomponent { contactform: formgroup = new formgroup({ name: new formcontrol(), phone: new formcontrol() })}
3)、关联组件模板中的表单
<form [formgroup]="contactform" (submit)="onsubmit()"> <input type="text" formcontrolname="name" /> <input type="text" formcontrolname="phone" /> <button>提交</button></form>
4)、获取表单值
export class appcomponent { onsubmit() { console.log(this.contactform.value) }}
5)、设置表单默认值
contactform: formgroup = new formgroup({ name: new formcontrol("默认值"), phone: new formcontrol(15888888888)})
6)、表单分组
contactform: formgroup = new formgroup({ fullname: new formgroup({ firstname: new formcontrol(), lastname: new formcontrol() }), phone: new formcontrol()})
<form [formgroup]="contactform" (submit)="onsubmit()"> <div formgroupname="fullname"> <input type="text" formcontrolname="firstname" /> <input type="text" formcontrolname="lastname" /> </div> <input type="text" formcontrolname="phone" /> <button>提交</button></form>
onsubmit() { console.log(this.contactform.value.name.username) console.log(this.contactform.get(["name", "username"])?.value)}
2.3 formarray
需求:在页面中默认显示一组联系方式,通过点击按钮可以添加更多联系方式组。
import { component, oninit } from "@angular/core"import { formarray, formcontrol, formgroup } from "@angular/forms"@component({ selector: "app-root", templateurl: "./app.component.html", styles: []})export class appcomponent implements oninit { // 表单 contactform: formgroup = new formgroup({ contacts: new formarray([]) }) get contacts() { return this.contactform.get("contacts") as formarray } // 添加联系方式 addcontact() { // 联系方式 const mycontact: formgroup = new formgroup({ name: new formcontrol(), address: new formcontrol(), phone: new formcontrol() }) // 向联系方式数组中添加联系方式 this.contacts.push(mycontact) } // 删除联系方式 removecontact(i: number) { this.contacts.removeat(i) } ngoninit() { // 添加默认的联系方式 this.addcontact() } onsubmit() { console.log(this.contactform.value) }}
<form [formgroup]="contactform" (submit)="onsubmit()"> <div formarrayname="contacts"> <div *ngfor="let contact of contacts.controls; let i = index" [formgroupname]="i" > <input type="text" formcontrolname="name" /> <input type="text" formcontrolname="address" /> <input type="text" formcontrolname="phone" /> <button (click)="removecontact(i)">删除联系方式</button> </div> </div> <button (click)="addcontact()">添加联系方式</button> <button>提交</button></form>
2.4 内置表单验证器
1)、使用内置验证器提供的验证规则验证表单字段
import { formcontrol, formgroup, validators } from "@angular/forms"contactform: formgroup = new formgroup({ name: new formcontrol("默认值", [ validators.required, validators.minlength(2) ])})
2)、获取整体表单是否验证通过
onsubmit() { console.log(this.contactform.valid)}
<!-- 表单整体未验证通过时禁用表单按钮 --><button [disabled]="contactform.invalid">提交</button>
3)、在组件模板中显示为验证通过时的错误信息
get name() { return this.contactform.get("name")!}
<form [formgroup]="contactform" (submit)="onsubmit()"> <input type="text" formcontrolname="name" /> <div *ngif="name.touched && name.invalid && name.errors"> <div *ngif="name.errors.required">请填写姓名</div> <div *ngif="name.errors.maxlength"> 姓名长度不能大于 {{ name.errors.maxlength.requiredlength }} 实际填写长度为 {{ name.errors.maxlength.actuallength }} </div> </div></form>
2.5 自定义同步表单验证器
自定义验证器的类型是 typescript 类
类中包含具体的验证方法,验证方法必须为静态方法
验证方法有一个参数 control,类型为 abstractcontrol。其实就是 formcontrol 类的实例对象的类型
如果验证成功,返回 null
如果验证失败,返回对象,对象中的属性即为验证标识,值为 true,标识该项验证失败
验证方法的返回值为 validationerrors | null
import { abstractcontrol, validationerrors } from "@angular/forms"export class namevalidators { // 字段值中不能包含空格 static cannotcontainspace(control: abstractcontrol): validationerrors | null { // 验证未通过 if (/\s/.test(control.value)) return { cannotcontainspace: true } // 验证通过 return null }}
import { namevalidators } from "./name.validators"contactform: formgroup = new formgroup({ name: new formcontrol("", [ validators.required, namevalidators.cannotcontainspace ])})
<div *ngif="name.touched && name.invalid && name.errors"> <div *ngif="name.errors.cannotcontainspace">姓名中不能包含空格</div></div>
2.6 自定义异步表单验证器
import { abstractcontrol, validationerrors } from "@angular/forms"import { observable } from "rxjs"export class namevalidators { static shouldbeunique(control: abstractcontrol): promise<validationerrors | null> { return new promise(resolve => { if (control.value == "admin") { resolve({ shouldbeunique: true }) } else { resolve(null) } }) }}
contactform: formgroup = new formgroup({ name: new formcontrol( "", [ validators.required ], namevalidators.shouldbeunique ) })
<div *ngif="name.touched && name.invalid && name.errors"> <div *ngif="name.errors.shouldbeunique">用户名重复</div></div><div *ngif="name.pending">正在检测姓名是否重复</div>
2.7 formbuilder
创建表单的快捷方式。
this.fb.control:表单项
this.fb.group:表单组,表单至少是一个 formgroup
this.fb.array:用于复杂表单,可以动态添加表单项或表单组,在表单验证时,formarray 中有一项没通过,整体没通过。
import { formbuilder, formgroup, validators } from "@angular/forms"export class appcomponent { contactform: formgroup constructor(private fb: formbuilder) { this.contactform = this.fb.group({ fullname: this.fb.group({ firstname: ["", [validators.required]], lastname: [""] }), phone: [] }) }}
2.8 监听表单值的变化
实际工作中,我们常常需要根据某个表单值得变化而进行相应的处理,一般可以使用ngmodalchange或者表单来实现
2.8.1 ngmodalchange
<div> <input type="text" [(ngmodal)]="name" (ngmodalchange)="namechange()" /></div>
import { formcontrol, formgroup } from "@angular/forms"export class appcomponent { public name = 'a'; public namechange() { }}
angular官方并不建议使用ngmodalchange。
2.8.2 表单控制
<div [formgroup]="contactform"> <input type="text" formcontrolname="name" /></div>
import { formcontrol, formgroup } from "@angular/forms"export class appcomponent { contactform: formgroup = new formgroup({ name: new formcontrol() }) ngonint() { this.contactform.get("name").valuechanges.subscribe(data => { console.log(data); } }}
2.9 练习
1)、获取一组复选框中选中的值
<form [formgroup]="form" (submit)="onsubmit()"> <label *ngfor="let item of data"> <input type="checkbox" [value]="item.value" (change)="onchange($event)" /> {{ item.name }} </label> <button>提交</button></form>
import { component } from "@angular/core"import { formarray, formbuilder, formgroup } from "@angular/forms"interface data { name: string value: string}@component({ selector: "app-checkbox", templateurl: "./checkbox.component.html", styles: []})export class checkboxcomponent { data: array<data> = [ { name: "pear", value: "pear" }, { name: "plum", value: "plum" }, { name: "kiwi", value: "kiwi" }, { name: "apple", value: "apple" }, { name: "lime", value: "lime" } ] form: formgroup constructor(private fb: formbuilder) { this.form = this.fb.group({ checkarray: this.fb.array([]) }) } onchange(event: event) { const target = event.target as htmlinputelement const checked = target.checked const value = target.value const checkarray = this.form.get("checkarray") as formarray if (checked) { checkarray.push(this.fb.control(value)) } else { const index = checkarray.controls.findindex( control => control.value === value ) checkarray.removeat(index) } } onsubmit() { console.log(this.form.value) }}
2)、获取单选框中选中的值
export class appcomponent { form: formgroup constructor(public fb: formbuilder) { this.form = this.fb.group({ gender: "" }) } onsubmit() { console.log(this.form.value) }}
<form [formgroup]="form" (submit)="onsubmit()"> <input type="radio" value="male" formcontrolname="gender" /> male <input type="radio" value="female" formcontrolname="gender" /> female <button type="submit">submit</button></form>
2.10 其他
patchvalue:设置表单控件的值(可以设置全部,也可以设置其中某一个,其他不受影响)
setvalue:设置表单控件的值 (设置全部,不能排除任何一个)
valuechanges:当表单控件的值发生变化时被触发的事件
reset:表单内容置空
更多编程相关知识,请访问:编程视频!!
以上就是angular学习之聊聊两种类型的表单的详细内容。