久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放AV片

<center id="vfaef"><input id="vfaef"><table id="vfaef"></table></input></center>

    <p id="vfaef"><kbd id="vfaef"></kbd></p>

    
    
    <pre id="vfaef"><u id="vfaef"></u></pre>

      <thead id="vfaef"><input id="vfaef"></input></thead>

    1. 站長(zhǎng)資訊網(wǎng)
      最全最豐富的資訊網(wǎng)站

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

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

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

      響應(yīng)式表單

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

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

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

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

      全局注冊(cè)響應(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

      使用表單控件有三個(gè)步驟。

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

      • 生成一個(gè)新的 FormControl 實(shí)例,并把它保存在組件中。

      • 在模板中注冊(cè)這個(gè) FormControl

      要注冊(cè)一個(gè)表單控件,就要導(dǎo)入FormControl類并創(chuàng)建一個(gè) FormControl的新實(shí)例,將其保存為類的屬性。如下: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è)置初始值,這個(gè)例子中它是空字符串   name = new FormControl(''); }

      然后在模板中注冊(cè)該控件,如下:test.component.html

      <!-- test.component.html --> <label>   Name: <input type="text" [formControl]="name"> </label> <!-- input 中輸入的值變化的話,這里顯示的值也會(huì)跟著變化 --> <p>name: {{ name.value }}</p>

      FormControl 的其它屬性和方法,參閱 API 參考手冊(cè)。

      https://angular.cn/api/forms/FormControl#formcontrol

      把表單控件分組 FormGroup

      就像FormControl 的實(shí)例能讓你控制單個(gè)輸入框所對(duì)應(yīng)的控件一樣,FormGroup 的實(shí)例也能跟蹤一組 FormControl 實(shí)例(比如一個(gè)表單)的表單狀態(tài)。當(dāng)創(chuàng)建 FormGroup 時(shí),其中的每個(gè)控件都會(huì)根據(jù)其名字進(jìn)行跟蹤。

      看下例演示: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 這個(gè) FormGroup 通過(guò) FormGroup 指令綁定到了 form 元素,在該模型和表單中的輸入框之間創(chuàng)建了一個(gè)通訊層 --> <!-- FormGroup 指令還會(huì)監(jiān)聽 form 元素發(fā)出的 submit 事件,并發(fā)出一個(gè) ngSubmit 事件,讓你可以綁定一個(gè)回調(diào)函數(shù)。 --> <form [formGroup]="profileForm" (ngSubmit)="onSubmit()">     <label> <!-- 由 FormControlName 指令把每個(gè)輸入框和 FormGroup 中定義的表單控件 FormControl 綁定起來(lái)。這些表單控件會(huì)和相應(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 參考手冊(cè)。

      https://angular.cn/api/forms/FormGroup#formgroup

      使用更簡(jiǎn)單的 FormBuilder 服務(wù)生成控件實(shí)例

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

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

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

      看下例演示: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)     } }

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

      表單驗(yàn)證器 Validators

      Validators類驗(yàn)證器的完整API列表,參考API手冊(cè)

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

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

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

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

      驗(yàn)證器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		// 最小長(zhǎng)度   static maxLength(maxLength: number): ValidatorFn		// 最大長(zhǎng)度   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)置驗(yàn)證器函數(shù)

      要使用內(nèi)置驗(yàn)證器,可以在實(shí)例化FormControl控件的時(shí)候添加

      import { Validators } from '@angular/forms'; ... ngOnInit(): void {   this.heroForm = new FormGroup({   // 實(shí)例化 FormControl 控件     name: new FormControl(this.hero.name, [       Validators.required,	// 驗(yàn)證,必填       Validators.minLength(4),	// 長(zhǎng)度不小于4       forbiddenNameValidator(/bob/i) // 自定義驗(yàn)證器     ]),     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'); }

      自定義驗(yàn)證器

      自定義驗(yàn)證器的內(nèi)容請(qǐng)參考API手冊(cè)

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

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

      • 在響應(yīng)式表單中添加自定義驗(yàn)證器。在上面內(nèi)置驗(yàn)證器一節(jié)中有一個(gè)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、添加自定義驗(yàn)證器       forbiddenNameValidator(/bob/i)     ])   }); } // 2、實(shí)現(xiàn)自定義驗(yàn)證器,功能為禁止輸入帶有 bob 字符串的值 export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {   return (control: AbstractControl): ValidationErrors | null => {     const forbidden = nameRe.test(control.value);     // 3、在值有效時(shí)返回 null,或無(wú)效時(shí)返回驗(yàn)證錯(cuò)誤對(duì)象     return forbidden ? {forbiddenName: {value: control.value}} : null;   }; }

        驗(yàn)證器在值有效時(shí)返回 null,或無(wú)效時(shí)返回驗(yàn)證錯(cuò)誤對(duì)象。 驗(yàn)證錯(cuò)誤對(duì)象通常有一個(gè)名為驗(yàn)證秘鑰(forbiddenName)的屬性。其值為一個(gè)任意詞典,你可以用來(lái)插入錯(cuò)誤信息({name})。

      • 在模板驅(qū)動(dòng)表單中添加自定義驗(yàn)證器。要為模板添加一個(gè)指令,該指令包含了 validator 函數(shù)。同時(shí),該指令需要把自己注冊(cè)成為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、注冊(cè)成為 NG_VALIDATORS 令牌的提供者   providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}] }) export class ForbiddenValidatorDirective implements Validator {   @Input('appForbiddenName') forbiddenName = '';   // 3、實(shí)現(xiàn) validator 接口,即實(shí)現(xiàn) validate 函數(shù)   validate(control: AbstractControl): ValidationErrors | null {   	// 在值有效時(shí)返回 null,或無(wú)效時(shí)返回驗(yàn)證錯(cuò)誤對(duì)象     return this.forbiddenName ? forbiddenNameValidator(new RegExp(this.forbiddenName, 'i'))(control)                               : null;   } } // 4、自定義驗(yàn)證函數(shù) export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {   return (control: AbstractControl): ValidationErrors | null => {     const forbidden = nameRe.test(control.value);     // 3、在值有效時(shí)返回 null,或無(wú)效時(shí)返回驗(yàn)證錯(cuò)誤對(duì)象     return forbidden ? {forbiddenName: {value: control.value}} : null;   }; }

        注意,自定義驗(yàn)證指令是用 useExisting 而不是 useClass 來(lái)實(shí)例化的。如果用useClass來(lái)代替 useExisting,就會(huì)注冊(cè)一個(gè)新的類實(shí)例,而它是沒有forbiddenName 的。

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

      贊(0)
      分享到: 更多 (0)
      網(wǎng)站地圖   滬ICP備18035694號(hào)-2    滬公網(wǎng)安備31011702889846號(hào)