• <fieldset id="8imwq"><menu id="8imwq"></menu></fieldset>
  • <bdo id="8imwq"><input id="8imwq"></input></bdo>
    最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
    問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
    當前位置: 首頁 - 科技 - 知識百科 - 正文

    angular6的響應式表單的實現

    來源:懂視網 責編:小采 時間:2020-11-27 22:06:17
    文檔

    angular6的響應式表單的實現

    angular6的響應式表單的實現:1:在AppModule模塊里面引入 ReactiveFormsModule 要使用響應式表單,就要從@angular/forms包中導入ReactiveFormsModule,并把它添加到你的NgModule的imports數組中。 import { ReactiveFormsModule } from '@angu
    推薦度:
    導讀angular6的響應式表單的實現:1:在AppModule模塊里面引入 ReactiveFormsModule 要使用響應式表單,就要從@angular/forms包中導入ReactiveFormsModule,并把它添加到你的NgModule的imports數組中。 import { ReactiveFormsModule } from '@angu

    1:在AppModule模塊里面引入 ReactiveFormsModule

    要使用響應式表單,就要從@angular/forms包中導入ReactiveFormsModule,并把它添加到你的NgModule的imports數組中。

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

    2:創建一個新的組件

    ng g c NameEditor

    3:請在組件中導入 FormControl 類

    FormControl類是angular響應式表單最基本的構造快,要注冊單個的表單控件,請在組件中導入FormControl類,并創建一個FormControl的新實例,把它保存在某個屬性里面。

    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 NameEditorComponent {
     name = new FormControl('');
    } 

    4:在組件的模板中注冊一個表單控件

    修改模板,為表單控件添加 formControl 綁定,formControl 是由 ReactiveFormsModule 中的 FormControlDirective 提供的。

    <label>
     Name:
     <input type="text" [formControl]="name">
    </label>
    
    <p>
     Value: {{ name.value }}
    </p>
    
    

    使用這種模板綁定語法,把該表單控件注冊給了模板中名為 name 的輸入元素。這樣,表單控件和 DOM
    元素就可以互相通訊了:視圖會反映模型的變化,模型也會反映視圖中的變化。

    5:替換表單控件的值

    FormControl 提供了一個setValue()方法,他會修改這個表單控件的值。

    js

     updateName() {
     this.name.setValue('Nancy');
     }
    

    html

    <label>
     Name:
     <input type="text" [formControl]="name">
    </label>
    <p>
     Value:{{name.value}}
    </p>
    <p>
     <button (click)="updateName()">Update Name</button>
    </p>
    

    在這個例子中,你只使用單個控件FormControl,但是當調用 FormGroup 或 FormArray 的 setValue()方法時,傳入的值就必須匹配控件組或控件數組的結構才行

    6:把表單控件分組

    FormControl的實例能控制單個輸入框所對應的控件,FormGroup可以控制一組FormControl實例的表單狀態,當創建FormGroup時,其中的每一個控件都會根據名字進行跟蹤

    1>:創建新的組件

    ng g c ProfileEditor

    2>:導入 FormGroup 和 FormControl 類并且創建 FormGroup實例

    import { Component } from '@angular/core';
    import { FormGroup, FormControl } from '@angular/forms';
     
    @Component({
     selector: 'app-profile-editor',
     templateUrl: './profile-editor.component.html',
     styleUrls: ['./profile-editor.component.css']
    })
    
    export class ProfileEditorComponent {
     profileForm = new FormGroup({
     firstName: new FormControl(''),
     lastName: new FormControl(''),
     });
    }
    
    

    現在這些單獨的控件FormControl被收集到了一個控件組中FormGroup, FormGroup 實例擁有和 FormControl 實例相同的屬性(比如 value、untouched)和方法(比如 setValue())。

    3>:關聯FormGroup的模型和視圖

    FormGroup能追蹤每個單獨控件FormControl的狀態和變化,如果其中某個控件的狀態或值變化了,父控件也會一次新的狀態變更或值變更事件

    <form [formGroup]="profileForm">
     
     <label>
     First Name:
     <input type="text" formControlName="firstName">
     </label>
    
     <label>
     Last Name:
     <input type="text" formControlName="lastName">
     </label>
    
    </form>
    
    

    profileForm通過[formGroup]指令綁定到了 form元素,在該模型和表單中的輸入框之間創建了一個通訊層,FormControlName 指令提供的 formControlName 屬性把每個輸入框和 FormGroup 中定義的表單控件綁定起來。

    4>:關聯FormGroup的模型和視圖

    html

     <form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
     <label>
     First Name:
     </label>
     <input type="text" formControlName="firstName">
     
     <label>
     Last Name:
     </label>
     <input type="text" formControlName="lastName">
     
     <button type="submit" >Submit</button>
     </form>

    js

    onSubmit () {
     console.warn(this.profileForm.value);
    }
    

    form 標簽所發出的 submit 事件是原生 DOM 事件,通過點擊類型為 submit 的按鈕可以觸發本事件

    6:嵌套的表單組

    js

    profileForm = new FormGroup({
     firstName: new FormControl(''),
     lastName: new FormControl(''),
     address: new FormGroup({
     street: new FormControl(''),
     city: new FormControl(''),
     state: new FormControl(''),
     zip: new FormControl('')
     })
    });
    

    html

    <form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
     <label>
     First Name:
     </label>
     <input type="text" formControlName="firstName">
     <label>
     Last Name:
     </label>
     <input type="text" formControlName="lastName">
    
     <div formGroupName="address">
     <label>Streel</label>
     <input type="text" formControlName="street">
     <label>City</label>
     <input type="text" formControlName="city">
     <label>State</label>
     <input type="text" formControlName="state">
     <label>Zip Code</label>
     <input type="text" formControlName="zip">
     </div>
    
     <button type="submit" [disabled]="!profileForm.valid">Submit</button>
    </form>
    
    

    部分模型修改

    html

    <button (click)="updateProfile()">Update Profile</button>

    js

    updateProfile() {
     this.profileForm.patchValue({
     firstName: 'Nancy',
     address: {
     street: '123 Drew Street'
     }
     });
    }
    

    patchValue() 方法要針對模型的結構進行更新。patchValue() 只會更新表單模型中所定義的那些屬性。

    6:使用 FormBuilder 來生成表單控件

    FormBuilder 服務提供了一些便捷方法來生成表單控件。

    FormBuilder在幕后也使用同樣的方式來創建和返回這些實例,只是用起來更簡單。 下面會重構 ProfileEditor 組件,用FormBuilder 來代替手工創建這些 FormControl 和 FormGroup。

    Step 1 - 導入 FormBuilder 類

    import { FormBuilder } from '@angular/forms';

    Step 2 - 注入FormBuild 服務

    constructor(private fb: FormBuilder) { }

    Step 3- 生成表單控件

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

    你可以使用 group() 方法,用和前面一樣的名字來定義這些屬性。這里,每個控件名對應的值都是一個數組,這個數組中的第一項是其初始值。你可以只使用初始值來定義控件,但是如果你的控件還需要同步或異步驗證器,那就在這個數組中的第二項和

    第三項提供同步和異步驗證器。

    import { Component } from '@angular/core';
    import { FormBuilder } from '@angular/forms';
     
    @Component({
     selector: 'app-profile-editor',
     templateUrl: './profile-editor.component.html',
     styleUrls: ['./profile-editor.component.css']
    })
    export class ProfileEditorComponent {
     profileForm = this.fb.group({
     firstName: ['張'],
     lastName: ['娉'],
     address: this.fb.group({
     street: [''],
     city: [''],
     state: [''],
     zip: ['']
     }),
     });
     
     constructor(private fb: FormBuilder) { }
    }

    7:簡單的表單驗證

    如何把單個驗證器添加到表單控件中,以及如何顯示表單的整體狀態。

    Step 1 - 導入驗證器函數

    import { Validators } from '@angular/forms';

    響應式表單包含了一組開箱即用的常用驗證器函數。這些函數接收一個控件,用以驗證并根據驗證結果返回一個錯誤對象或空值。

    Step 2 - 把字段設為必填

    最常見的校驗項是把一個字段設為必填項。本節描述如何為 firstName 控件添加“必填項”驗證器。

    在組件中,把靜態方法 Validators.required 設置為 firstName 控件值數組中的第二項。

    profileForm = this.fb.group({
     firstName: ['', Validators.required],
     lastName: [''],
     address: this.fb.group({
     street: [''],
     city: [''],
     state: [''],
     zip: ['']
     }),
    });
    

    HTML5 有一組內置的屬性,用來進行原生驗證,包括 required、minlength、maxlength等。雖然是可選的,不過你也可以在表單的輸入元素上把它們添加為附加屬性來使用它們。這里我們把 required 屬性添加到 firstName輸入元素上。

    <input type="text" formControlName="firstName" required>
    

    這些 HTML5 驗證器屬性可以和 Angular響應式表單提供的內置驗證器組合使用。組合使用這兩種驗證器實踐,可以防止在模板檢查完之后表達式再次被修改導致的錯誤。

    8:顯示表單的狀態

    現在,你已經往表單控件上添加了一個必填字段,它的初始值是無效的(invalid)。這種無效狀態冒泡到其父 FormGroup 中,也讓這個 FormGroup 的狀態變為無效的。你可以通過該 FormGroup 實例的 status 屬性來訪問其當前狀態。

    <p>
     Form Status: {{ profileForm.status }}
    </p>
    

    9:使用表單數組管理動態控件

    FormArray 是 FormGroup 之外的另一個選擇,用于管理任意數量的匿名控件,如果你事先不知道子控件的數量,FormArray是一個很好的選擇

    Step 1 - 導入 FormArray

    import { FormArray } from '@angular/forms';

    Step 2 - 定義 FormArray

    為 profileForm 添加一個 aliases 屬性,把它定義為 FormArray 類型。(FormBuilder 服務用于創建 FormArray 實例。)

    profileForm = this.fb.group({
     firstName: ['張', Validators.required],
     lastName: ['以'],
     address: this.fb.group({
     street: [''],
     city: [''],
     state: [''],
     zip: ['']
     }),
     aliases: this.fb.array([
     this.fb.control('')
     ])
     });
    

    Step 3 - 訪問FormArray控件

    通過 getter 來訪問控件比較便捷,也容易復用

    使用 getter 語法來創建一個名為 aliases 的類屬性

    get aliases() {
     
    }
    

    從父控件 FormGroup 中接收綽號的 FormArray 控件。

    get aliases() {
     return this.profileForm.get('aliases') as FormArray;
    }
    addAlias() {
     this.aliases.push(this.fb.control(''));
    }
    

    Step 3 - 在模板中顯示表單數組

    在模型中定義了 aliases 的 FormArray 之后,你必須把它加入到模板中供用戶輸入,使用 formArrayName 在這個
    FormArray 和模板之間建立綁定。

    <div formArrayName="aliases">
     <h3>Aliases</h3> <button (click)="addAlias()">Add Alias</button>
    
     <div *ngFor="let address of aliases.controls; let i=index">
     <!-- The repeated alias template -->
     <label>
     Alias:
     <input type="text" [formControlName]="i">
     </label>
     </div>
    </div>
    
    

    每當新的 alias 加進來時,FormArray 就會基于這個索引號提供它的控件。這將允許你在每次計算根控件的狀態和值時跟蹤每個控件。

    全部代碼

    html

    <form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
     <label>
     First Name:
     </label>
     <input type="text" formControlName="firstName" required>
    
     <label>
     Last Name:
     </label>
     <input type="text" formControlName="lastName">
    
     <div formGroupName="address">
     <h3>Address</h3>
     <label>Streel</label>
     <input type="text" formControlName="street">
    
     <label>City</label>
     <input type="text" formControlName="city">
     
     <label>State</label>
     <input type="text" formControlName="state">
    
     <label>Zip Code</label>
     <input type="text" formControlName="zip">
     </div>
    
     <div formArrayName="aliases">
     <h3>Aliases</h3>
     <button (click)="addAlias()">Add Alias</button>
     
     <div *ngFor="let address of aliases.controls; let i=index">
     <label>Alias</label>
     <input type="text" [formControlName]="i" >
     </div>
     </div>
    
     <button type="submit" [disabled]="!profileForm.valid">Submit</button>
     <p>
     <button (click)="updateProfile()">Update Profile</button>
     </p>
    
     <p>
     Form Status: {{ profileForm.status }}
     </p>
    </form>

    js

    import { Component, OnInit } from '@angular/core';
    import {FormControl, FormGroup, FormBuilder, Validators, FormArray} from '@angular/forms';
    
    @Component({
     selector: 'app-profile-editor',
     templateUrl: './profile-editor.component.html',
     styleUrls: ['./profile-editor.component.css']
    })
    export class ProfileEditorComponent implements OnInit {
     profileForm = this.fb.group({
     firstName: ['張', Validators.required],
     lastName: ['以'],
     address: this.fb.group({
     street: [''],
     city: [''],
     state: [''],
     zip: ['']
     }),
     aliases: this.fb.array([
     this.fb.control('')
     ])
     });
     constructor(private fb: FormBuilder) {
    
     }
    
     ngOnInit() {
     }
    
     onSubmit () {
     console.warn(this.profileForm.value);
     }
     
     updateProfile() {
     this.profileForm.patchValue({
     firstName: 'Nancy',
     address: {
     street: '123 Drew Street'
     }
     });
     }
     get aliases () {
     return this.profileForm.get('aliases') as FormArray;
     }
     addAlias() {
     this.aliases.push(this.fb.control(''));
     }
    }

    聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

    文檔

    angular6的響應式表單的實現

    angular6的響應式表單的實現:1:在AppModule模塊里面引入 ReactiveFormsModule 要使用響應式表單,就要從@angular/forms包中導入ReactiveFormsModule,并把它添加到你的NgModule的imports數組中。 import { ReactiveFormsModule } from '@angu
    推薦度:
    標簽: 表單 響應式 form
    • 熱門焦點

    最新推薦

    猜你喜歡

    熱門推薦

    專題
    Top
    主站蜘蛛池模板: 99久久国语露脸精品国产| 国产精品扒开腿做爽爽爽视频| 亚洲av永久无码精品古装片| 91精品成人免费国产片 | 成人精品在线视频| 在线亚洲精品福利网址导航| 四虎国产精品永久一区| 精品国产一区二区三区不卡 | 久久99精品国产自在现线小黄鸭| 热久久国产欧美一区二区精品| 国产成人精品一区在线| 国产精品www| 国产午夜无码精品免费看| 在线精品动漫一区二区无广告| 精品国产国产综合精品| 99久久国产综合精品网成人影院 | 久久国产亚洲精品无码| 亚洲精品无码av天堂| 另类国产精品一区二区| 国产精品美女久久久久AV福利| 中文精品一卡2卡3卡4卡| 国产一成人精品福利网站| 国产高清在线精品二区一| 国产l精品国产亚洲区在线观看| 久久狠狠高潮亚洲精品| 久久精品无码午夜福利理论片| 亚洲av无码精品网站| 亚洲精品乱码久久久久久中文字幕| 四虎成人精品国产永久免费无码| 久久精品国产亚洲一区二区三区| 国内精品国产成人国产三级| 国产亚洲精品自在线观看| 国产精品最新国产精品第十页 | 亚洲精品无码国产| 亚洲国产第一站精品蜜芽| 亚洲精品线路一在线观看| 亚洲精品成a人在线观看| 亚洲欧洲久久久精品| 亚洲精品无码专区在线在线播放 | 宅男在线国产精品无码| 亚洲一区二区三区国产精品|