站長資訊網
        最全最豐富的資訊網站

        angular學習之淺析響應式表單

        本篇文章帶大家繼續angular的學習,了解一下angular中的響應式表單,介紹一下全局注冊響應式表單模塊、添加基礎表單控件的相關知識,希望對大家有所幫助!

        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

        要注冊一個表單控件,就要導入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)函數可以是同步函數,也可以是異步函數。

        • 同步驗證器:這些同步函數接受一個控件實例,然后返回一組驗證錯誤或 null。你可以在實例化一個 FormControl 時把它作為構造函數的第二個參數傳進去。
        • 異步驗證器 :這些異步函數接受一個控件實例并返回一個 PromiseObservable,它稍后會發出一組驗證錯誤或 null。在實例化 FormControl 時,可以把它們作為第三個參數傳入。

        出于性能方面的考慮,只有在所有同步驗證器都通過之后,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

        有時候內置的驗證器并不能很好的滿足需求,比如,我們需要對一個表單進行驗證,要求輸入的值只能為某一個數組中的值,而這個數組中的值是隨程序運行實時改變的,這個時候內置的驗證器就無法滿足這個需求,需要創建自定義驗證器。

        • 在響應式表單中添加自定義驗證器。在上面內置驗證器一節中有一個forbiddenNameValidator函數如下:

          import { Validators } from '@angular/forms'; ... ngOnInit(): void {   this.heroForm = new FormGroup({     name: new FormControl(this.hero.name, [       Validators.required,       Validators.minLength(4),       // 1、添加自定義驗證器       forbiddenNameValidator(/bob/i)     ])   }); } // 2、實現自定義驗證器,功能為禁止輸入帶有 bob 字符串的值 export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {   return (control: AbstractControl): ValidationErrors | null => {     const forbidden = nameRe.test(control.value);     // 3、在值有效時返回 null,或無效時返回驗證錯誤對象     return forbidden ? {forbiddenName: {value: control.value}} : null;   }; }

          驗證器在值有效時返回 null,或無效時返回驗證錯誤對象。 驗證錯誤對象通常有一個名為驗證秘鑰(forbiddenName)的屬性。其值為一個任意詞典,你可以用來插入錯誤信息({name})。

        • 在模板驅動表單中添加自定義驗證器。要為模板添加一個指令,該指令包含了 validator 函數。同時,該指令需要把自己注冊成為NG_VALIDATORS的提供者。如下所示:

          // 1、導入相關類 import { NG_VALIDATORS, Validator, AbstractControl, ValidationErrors } from '@angular/forms'; import { Input } from '@angular/core'  @Directive({   selector: '[appForbiddenName]',   // 2、注冊成為 NG_VALIDATORS 令牌的提供者   providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}] }) export class ForbiddenValidatorDirective implements Validator {   @Input('appForbiddenName') forbiddenName = '';   // 3、實現 validator 接口,即實現 validate 函數   validate(control: AbstractControl): ValidationErrors | null {   	// 在值有效時返回 null,或無效時返回驗證錯誤對象     return this.forbiddenName ? forbiddenNameValidator(new RegExp(this.forbiddenName, 'i'))(control)                               : null;   } } // 4、自定義驗證函數 export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {   return (control: AbstractControl): ValidationErrors | null => {     const forbidden = nameRe.test(control.value);     // 3、在值有效時返回 null,或無效時返回驗證錯誤對象     return forbidden ? {forbiddenName: {value: control.value}} : null;   }; }

          注意,自定義驗證指令是用 useExisting 而不是 useClass 來實例化的。如果用useClass來代替 useExisting,就會注冊一個新的類實例,而它是沒有forbiddenName 的。

          <input type="text" required appForbiddenName="bob" [(ngModel)]="hero.name">

        贊(0)
        分享到: 更多 (0)
        網站地圖   滬ICP備18035694號-2    滬公網安備31011702889846號
        主站蜘蛛池模板: 亚洲日韩中文在线精品第一| 国产福利在线观看精品| 日韩精品国产另类专区| 国产激情精品一区二区三区| 久久久久人妻一区精品色| 久久久久久极精品久久久| 亚洲精品线在线观看| 精品视频一区二区三三区四区| 蜜桃麻豆www久久国产精品| 88久久精品无码一区二区毛片| 99热门精品一区二区三区无码 | 国产精品丝袜一区二区三区| 青草青草久热精品视频在线观看| 国产精品第一区第27页| 精品福利一区二区三| 500av大全导航精品| 国产精品视频一区二区三区四 | 久久Av无码精品人妻系列| 尤物国精品午夜福利视频| 久久国产精品免费一区| 国产精品综合专区中文字幕免费播放| 日韩精品在线视频| 亚洲国产成人精品不卡青青草原 | 香港aa三级久久三级老师2021国产三级精品三级在 | 精品视频无码一区二区三区| 亚洲精品午夜无码电影网| 亚洲精品97久久中文字幕无码| 久久精品国产福利国产琪琪| 国产精品女同一区二区久久| 丁香色婷婷国产精品视频| 99久久精品无码一区二区毛片| 在线观看日韩精品| 四虎国产精品永久地址99| 亚洲国产精品久久久久久| 日韩精品免费在线视频| 国产69精品久久久久9999| 国产精品成人啪精品视频免费| 91精品国产自产在线观看| 国产精品久久久久久久午夜片 | 天天爽夜夜爽8888视频精品| 日韩精品无码Av一区二区|