亚洲最大看欧美片,亚洲图揄拍自拍另类图片,欧美精品v国产精品v呦,日本在线精品视频免费

  • 站長資訊網(wǎng)
    最全最豐富的資訊網(wǎng)站

    angular學(xué)習(xí)之淺析響應(yīng)式表單

    本篇文章帶大家繼續(xù)angular的學(xué)習(xí),了解一下angular中的響應(yīng)式表單,介紹一下全局注冊響應(yīng)式表單模塊、添加基礎(chǔ)表單控件的相關(guān)知識,希望對大家有所幫助!

    angular學(xué)習(xí)之淺析響應(yīng)式表單

    響應(yīng)式表單

    Angular 提供了兩種不同的方法來通過表單處理用戶輸入:響應(yīng)式表單模板驅(qū)動表單?!鞠嚓P(guān)教程推薦:《angular教程》】

    • 響應(yīng)式表單:提供對底層表單對象模型直接、顯式的訪問。它們與模板驅(qū)動表單相比,更加健壯。如果表單是你的應(yīng)用程序的關(guān)鍵部分,或者你已經(jīng)在使用響應(yīng)式表單來構(gòu)建應(yīng)用,那就使用響應(yīng)式表單。
    • 模板驅(qū)動表單:依賴模板中的指令來創(chuàng)建和操作底層的對象模型。它們對于向應(yīng)用添加一個簡單的表單非常有用,比如電子郵件列表注冊表單。

    這里只介紹響應(yīng)式表單,模板驅(qū)動表單請參考官網(wǎng):

    https://angular.cn/guide/forms-overview#setup-in-template-driven-forms

    全局注冊響應(yīng)式表單模塊 ReactiveFormsModule

    要使用響應(yīng)式表單控件,就要從 @angular/forms 包中導(dǎo)入 ReactiveFormsModule,并把它添加到你的 NgModuleimports數(shù)組中。如下:app.module.ts

    /***** app.module.ts *****/ import { ReactiveFormsModule } from '@angular/forms';  @NgModule({   imports: [     // other imports ...     ReactiveFormsModule   ], }) export class AppModule { }

    添加基礎(chǔ)表單控件 FormControl

    使用表單控件有三個步驟。

    • 在你的應(yīng)用中注冊響應(yīng)式表單模塊。該模塊聲明了一些你要用在響應(yīng)式表單中的指令。

    • 生成一個新的 FormControl 實例,并把它保存在組件中。

    • 在模板中注冊這個 FormControl。

    要注冊一個表單控件,就要導(dǎo)入FormControl類并創(chuàng)建一個 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 的構(gòu)造函數(shù)設(shè)置初始值,這個例子中它是空字符串   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 的實例能讓你控制單個輸入框所對應(yīng)的控件一樣,FormGroup 的實例也能跟蹤一組 FormControl 實例(比如一個表單)的表單狀態(tài)。當(dāng)創(chuàng)建 FormGroup 時,其中的每個控件都會根據(jù)其名字進行跟蹤。

    看下例演示:test.component.ts、test.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 元素,在該模型和表單中的輸入框之間創(chuàng)建了一個通訊層 --> <!-- FormGroup 指令還會監(jiān)聽 form 元素發(fā)出的 submit 事件,并發(fā)出一個 ngSubmit 事件,讓你可以綁定一個回調(diào)函數(shù)。 --> <form [formGroup]="profileForm" (ngSubmit)="onSubmit()">     <label> <!-- 由 FormControlName 指令把每個輸入框和 FormGroup 中定義的表單控件 FormControl 綁定起來。這些表單控件會和相應(yīng)的元素通訊 -->       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>   <!-- 控件組的狀態(tài): 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 服務(wù)生成控件實例

    在響應(yīng)式表單中,當(dāng)需要與多個表單打交道時,手動創(chuàng)建多個表單控件實例會非常繁瑣。FormBuilder服務(wù)提供了一些便捷方法來生成表單控件。FormBuilder在幕后也使用同樣的方式來創(chuàng)建和返回這些實例,只是用起來更簡單。

    FormBuilder 是一個可注入的服務(wù)提供者,它是由 ReactiveFormModule 提供的。只要把它添加到組件的構(gòu)造函數(shù)中就可以注入這個依賴。

    FormBuilder服務(wù)有三個方法:control()、group()array()。這些方法都是工廠方法,用于在組件類中分別生成FormControlFormGroupFormArray。

    看下例演示:test.component.ts

    import { Component } from '@angular/core'; // 1、導(dǎo)入 FormBuilder import { FormBuilder, Validators } from '@angular/forms';  @Component({   selector: 'app-test',   templateUrl: './test.component.html',   styleUrls: ['./test.component.css'] }) export class TestComponent { 	// 2、注入 FormBuilder 服務(wù)     constructor(private fb: FormBuilder) { }     ngOnInit() { }      profileForm = this.fb.group({       firstName: ['', [Validators.required, Validators.pattern('[a-zA-Z0-9]*')]],       lastName: ['', Validators.required],     });     // 相當(dāng)于     // 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)     } }

    對比可以發(fā)現(xiàn),使用FormBuilder服務(wù)可以更方便地生成FormControl、FormGroupFormArray,而不必每次都手動new一個新的實例出來。

    表單驗證器 Validators

    Validators類驗證器的完整API列表,參考API手冊

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

    驗證器(Validators)函數(shù)可以是同步函數(shù),也可以是異步函數(shù)。

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

    出于性能方面的考慮,只有在所有同步驗證器都通過之后,Angular 才會運行異步驗證器。當(dāng)每一個異步驗證器都執(zhí)行完之后,才會設(shè)置這些驗證錯誤。

    驗證器Validators類的API

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

    class Validators {   static min(min: number): ValidatorFn		// 允許輸入的最小數(shù)值   static max(max: number): ValidatorFn		// 最大數(shù)值   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 }

    內(nèi)置驗證器函數(shù)

    要使用內(nèi)置驗證器,可以在實例化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'); }

    自定義驗證器

    自定義驗證器的內(nèi)容請參考API手冊

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

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

    • 在響應(yīng)式表單中添加自定義驗證器。在上面內(nèi)置驗證器一節(jié)中有一個forbiddenNameValidator函數(shù)如下:

      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、實現(xiàn)自定義驗證器,功能為禁止輸入帶有 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})。

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

      // 1、導(dǎo)入相關(guān)類 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、實現(xiàn) validator 接口,即實現(xiàn) validate 函數(shù)   validate(control: AbstractControl): ValidationErrors | null {   	// 在值有效時返回 null,或無效時返回驗證錯誤對象     return this.forbiddenName ? forbiddenNameValidator(new RegExp(this.forbiddenName, 'i'))(control)                               : null;   } } // 4、自定義驗證函數(shù) 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)
    網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號