注冊響應(yīng)式表單模塊
要使用響應(yīng)式表單控件渐排,就要在app.module.ts
文件中勉吻,從 @angular/forms
包中導(dǎo)入 [ReactiveFormsModule](https://angular.cn/api/forms/ReactiveFormsModule)
,并把它添加到你的 NgModule 的 imports
數(shù)組中。
1、組件中引入import { FormControl,FormBuilder,FormGroup, Validators } from '@angular/forms';
表單驗證模塊(FormGroup:表單驗證組內(nèi)部有FormControl又谋,F(xiàn)ormBuilder:ts中使用其創(chuàng)建表單對象拼缝,Validators:Angular內(nèi)含的驗證模塊)
2、在頁面中創(chuàng)建表單組件彰亥,表單綁定[formGroup]='form'
屬性咧七;在ts中定義public form!:FormGroup
。同時在html頁面中需要驗證的表單元素中綁定formControlName='username'
<input nz-input type="text" formControlName='username' required placeholder="用戶名">
<input nz-input type="text" formControlName='password' placeholder="密碼">
3剩愧、聲明表單初始化函數(shù)(兩種方法)猪叙,在組件的初始化生命周期中進行調(diào)用
//初始化表單
initform(){
//使用構(gòu)造函數(shù)方法創(chuàng)建表單對象
// this.form=new FormGroup({
// username:new FormControl('',[Validators.required]),
// password:new FormControl('',[Validators.required])
// })
//使用FormBuilder模塊中的group方法創(chuàng)建表單對象
this.form=this.FormBuilder.group({
username:['',[Validators.required,Validators.maxLength(8)]],
password:['',Validators.required]
})
}
4、使用get方法獲取兩個表單項,方便后面對頁面中對提示函數(shù)的書寫不用多次獲取表單的項目
public get username() {
return this.form.get('username')
}
public get password() {
return this.form.get('password')
}
5仁卷、定義表單驗證不通過提示函數(shù)
getErrorMsg(name:any){
switch (name) {
case 'username':
return this.username?.errors?.required?'用戶名必填':
this.username?.errors?.maxlength?'用戶名不能超過8位':
'';
break;
case 'password':
return this.password?.errors?.required?'密碼必填':'';
break;
default:
return false
break;
}
}
6穴翩、在頁面中想要顯示提示錯誤的地方引用
//username項驗證不通過提示
<div [ngStyle]="{'color':'red'}">{{getErrorMsg('username')}}</div>
//password項驗證不通過提示
<div [ngStyle]="{'color':'red'}">{{getErrorMsg('password')}}</div>
7、在表單提交事件中對表單驗證是否通過進行判斷锦积,是否提交表單
functionName(){
if (this.form.valid) {
//通過驗證芒帕,使用this.form.value獲取表單提交的值
console.log(this.form.value);
}else{
//未通過驗證,調(diào)用內(nèi)置的提示模塊給出提示
for (const i in this.validateForm.controls) {
if (this.validateForm.controls.hasOwnProperty(i)) {
this.validateForm.controls[i].markAsDirty();
this.validateForm.controls[i].updateValueAndValidity();
}
}
}
}
以下為具體代碼
//html
<form (ngSubmit)="functionName()" [formGroup]='form'>
<div>
<input nz-input type="text" formControlName='username' required placeholder="用戶名">
<div [ngStyle]="{'color':'red'}">{{getErrorMsg('username')}}</div>
</div>
<div>
<input nz-input type="text" formControlName='password' placeholder="密碼">
<div [ngStyle]="{'color':'red'}">{{getErrorMsg('password')}}</div>
</div>
<button type="submit">提交</button>
</form>
//ts
import { Component, OnInit } from '@angular/core';
import { FormControl,FormBuilder,FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-form-valid',
templateUrl: './form-valid.component.html',
styleUrls: ['./form-valid.component.scss']
})
export class FormValidComponent implements OnInit {
public form!:FormGroup
constructor(private FormBuilder:FormBuilder) { }
//表單提交
functionName(){
if (this.form.valid) {
//通過驗證丰介,使用this.form.value獲取表單提交的值
console.log(this.form.value);
}else{
//未通過驗證背蟆,調(diào)用內(nèi)置的提示模塊給出提示
for (const i in this.validateForm.controls) {
if (this.validateForm.controls.hasOwnProperty(i)) {
this.validateForm.controls[i].markAsDirty();
this.validateForm.controls[i].updateValueAndValidity();
}
}
}
}
public get username() {
return this.form.get('username')
}
public get password() {
return this.form.get('password')
}
getErrorMsg(name:any){
switch (name) {
case 'username':
return this.username?.errors?.required?'用戶名必填':
this.username?.errors?.maxlength?'用戶名不能超過8位':
'';
break;
case 'password':
return this.password?.errors?.required?'密碼必填':'';
break;
default:
return false
break;
}
}
//初始化表單
initform(){
// this.form=new FormGroup({
// username:new FormControl('',[Validators.required]),
// password:new FormControl('',[Validators.required])
// })
this.form=this.FormBuilder.group({
username:['',[Validators.required,Validators.maxLength(8)]],
password:['',Validators.required]
})
}
ngOnInit(): void {
this.initform()
}
}