這篇文章帶大家了解一下Angular中兩種Form表單,簡單介紹一下它們的用法,希望對大家有幫助!
在 Angular
中,表單有兩種類型,分別為範本驅動和模型驅動。 【相關教學推薦:《angular教學》】
1. 模板驅動
##1.1 概述
表單的控制邏輯寫在元件範本中,適合簡單的表單類型#1.2 快速上手
引入依賴模組 FormsModule
import { FormsModule } from "@angular/forms" @NgModule({ imports: [FormsModule], }) export class AppModule {}將
DOM 表單轉換為
ngForm
<form #f="ngForm" (submit)="onSubmit(f)"></form>聲明表單欄位為
ngModel
<form #f="ngForm" (submit)="onSubmit(f)"> <input type="text" name="username" ngModel /> <button>提交</button> </form>取得表單欄位值
import { NgForm } from "@angular/forms" export class AppComponent { onSubmit(form: NgForm) { console.log(form.value) } }表單分組
<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>
1.3 表單驗證
#填欄位
欄位最小長度
欄位最大長度
# 驗證正規例如:
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. 模型驅動
2.1 概述
#表單的控制邏輯寫在元件類別中,對驗證邏輯擁有更多的控制權,適合複雜的表單的類型。 在模型驅動表單中,表單欄位需要是FormControl 類別的實例,實例物件可以驗證表單欄位中的值,值是否被修改過等等
FormGroup 類別的實例,它可以對表單進行整體驗證
FormControl:表單群組中的表單項目
FormGroup:表單群組,表單至少是一個
FormGroup
FormArray:用於複雜表單,可以動態新增表單項目或表單組,在表單驗證時,
FormArray 中有一項沒通過,整體沒透過
#2.2 快速上手
引入ReactiveFormsModule
import { ReactiveFormsModule } from "@angular/forms" @NgModule({ imports: [ReactiveFormsModule] }) export class AppModule {}在元件類別中建立
FormGroup 表單控制物件
import { FormControl, FormGroup } from "@angular/forms" export class AppComponent { contactForm: FormGroup = new FormGroup({ name: new FormControl(), phone: new FormControl() }) }關聯元件範本中的表單
<form [formGroup]="contactForm" (submit)="onSubmit()"> <input type="text" formControlName="name" /> <input type="text" formControlName="phone" /> <button>提交</button> </form>取得表單值
export class AppComponent { onSubmit() { console.log(this.contactForm.value) } }設定表單預設值
contactForm: FormGroup = new FormGroup({ name: new FormControl("默认值"), phone: new FormControl(15888888888) })表單分組
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 內建表單驗證器##使用內建驗證器提供的驗證規則驗證表單欄位
import { FormControl, FormGroup, Validators } from "@angular/forms" contactForm: FormGroup = new FormGroup({ name: new FormControl("默认值", [ Validators.required, Validators.minLength(2) ]) })
取得整體表單是否驗證透過
onSubmit() { console.log(this.contactForm.valid) }
<!-- 表单整体未验证通过时禁用表单按钮 --> <button [disabled]="contactForm.invalid">提交</button>
在元件範本中顯示為驗證通過時的錯誤訊息
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 自訂同步表單驗證器
類別
,類型為AbstractControl
。其實就是FormControl
類別的實例物件的型別
,標識該項驗證失敗
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>
import { AbstractControl, ValidationErrors } from "@angular/forms"
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>
FormBuilder 建立表單的捷徑。
:表單項目
:表單群組,表單至少是一個FormGroup
:用於複雜表單,可以動態新增表單項目或表單群組,表單驗證時,FormArray
中有一項沒通過,整體沒通過
##2.8 練習
取得一組複選框中選取的值
<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) } }取得單選方塊中選取的值
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.9 其他
patchValue
:设置表单控件的值(可以设置全部,也可以设置其中某一个,其他不受影响)
setValue
:设置表单控件的值 (设置全部,不能排除任何一个)
valueChanges
:当表单控件的值发生变化时被触发的事件
reset
:表单内容置空
updateValueAndValidity
:对指定输入框 取消校验
validateForm: FormGroup; this.validateForm.get('cpwd').updateValueAndValidity();
更多编程相关知识,请访问:编程视频!!
以上是淺析Angular中兩種類型的Form表單的詳細內容。更多資訊請關注PHP中文網其他相關文章!