14.《Angular響應(yīng)式表單》

一、使用響應(yīng)式表單

Angular 的響應(yīng)式表單能讓實(shí)現(xiàn)響應(yīng)式編程風(fēng)格更容易,這種編程風(fēng)格更傾向于在非 UI 的數(shù)據(jù)模型(通常接收自服務(wù)器)之間顯式的管理數(shù)據(jù)流, 并且用一個(gè) UI 導(dǎo)向的表單模型來保存屏幕上 HTML 控件的狀態(tài)和值。 響應(yīng)式表單可以讓使用響應(yīng)式編程模式、測(cè)試和校驗(yàn)變得更容易。

響應(yīng)式表單.png

二、代碼示例

//新建react-form組件
ng g component reactive-form
//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { ReactiveFormComponent } from './reactive-form/reactive-form.component';


@NgModule({
  declarations: [
    AppComponent,
    ReactiveFormComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

//app.component.html
<app-reactive-form></app-reactive-form>
//react-form.component.html
<form [formGroup]="formModel" (submit)="onSubmit()">
  <div formArrayName="dateRange">
    起始日期:<input formControlName="form" type="date">
    截止日期:<input formControlName="to" type="date">
  </div>
  <div>
    <ul formArrayName="emails">
      <li *ngFor="let e of formModel.get('emails').controls;let i = index;">
        <input type="text" [formControlName]="i">
      </li>
    </ul>
    <button type="button" (click)="addEmail()">增加Email</button>
    <button type="submit">保存</button>
  </div>
</form>

//react-form.component.ts
import {Component, OnInit} from '@angular/core';
import {FormArray, FormControl, FormGroup} from '@angular/forms';

@Component({
  selector: 'app-reactive-form',
  templateUrl: './reactive-form.component.html',
  styleUrls: ['./reactive-form.component.css']
})
export class ReactiveFormComponent implements OnInit {

  //FormControl 構(gòu)造函數(shù)接收一個(gè)參數(shù),這里是aaa,這個(gè)參數(shù)用來指定FormControl的初始值,當(dāng)此FormControl與頁面中input關(guān)聯(lián)時(shí),input的初始值為aaa
  username: FormControl = new FormControl('aaa');

  formModel: FormGroup = new FormGroup({
    dateRange: new FormGroup({
      form: new FormControl(),
      to: new FormControl()
    }),
    emails: new FormArray([
      new FormControl('@we'),
      new FormControl('@234234')
    ])
  });


  constructor() {
  }

  ngOnInit() {
  }

  onSubmit() {
    console.log(this.formModel.value);
  }

  addEmail() {
    let emails = this.formModel.get('emails') as FormArray;
    emails.push(new FormControl());

  }

}
運(yùn)行結(jié)果1.png

制作一個(gè)響應(yīng)式的注冊(cè)表單

//新建響應(yīng)式的表單注冊(cè)組件
ng g component react-regist
//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import { Form1Component } from './form1/form1.component';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { HeroFormComponent } from './hero-form/hero-form.component';
import { ReactiveFormComponent } from './reactive-form/reactive-form.component';
import { ReactRegistComponent } from './react-regist/react-regist.component';


@NgModule({
  declarations: [
    AppComponent,
    ReactRegistComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

//app.component.html
<app-react-regist></app-react-regist>
//react-regist.component.html
<form [formGroup]="formModel" (submit)="onSubmit()">
  <div>電話:<input formControlName="mobile" type="text" name="mobile"/></div>
  <div>用戶名:<input formControlName="username" type="text" name="username"/></div>
  <div formGroupName="passwordsGroup">
    <div>密碼:<input formControlName="password" type="password" name="password"/></div>
    <div>確認(rèn)密碼:<input formControlName="confirmPass" type="password" name="confirmPass"/></div>
  </div>
  <div>
    <button type="submit">提交</button>
  </div>
</form>

//react-regist.component.ts
import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';

@Component({
  selector: 'app-react-regist',
  templateUrl: './react-regist.component.html',
  styleUrls: ['./react-regist.component.css']
})
export class ReactRegistComponent implements OnInit {
  formModel: FormGroup;

  constructor() {
   this.formModel = new FormGroup({
      mobile: new FormControl('18249666846'),
      username: new FormControl('xiaoming'),
      passwordsGroup: new FormGroup({
        password: new FormControl(),
        confirmPass: new FormControl()
      })
    });
  }

  ngOnInit() {}

  onSubmit() {
    console.log(this.formModel.value);
  }
}
//使用FormBuilder重構(gòu)上面的react-regist.component.ts
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from '@angular/forms';

@Component({
  selector: 'app-react-regist',
  templateUrl: './react-regist.component.html',
  styleUrls: ['./react-regist.component.css']
})
export class ReactRegistComponent implements OnInit {
  formModel: FormGroup;

  constructor(fb: FormBuilder) {
    this.formModel = fb.group({
      mobile: ['18249666846'],
      username: ['xiaoming'],
      passwordsGroup: fb.group({
        password: [''],
        confirmPass: ['']
      })
    });
  }

  ngOnInit() {}

  onSubmit() {
    console.log(this.formModel.value);
  }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Angular響應(yīng)式表單相比較模板驅(qū)動(dòng)表單更大操作性、更易測(cè)試性。因此,我更推薦這類表單創(chuàng)造方式。 當(dāng)一個(gè)用于修改...
    cipchk閱讀 1,263評(píng)論 0 2
  • 1、通過CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫(kù)組件 SD...
    陽明AI閱讀 16,204評(píng)論 3 119
  • 年關(guān)將至,疲于奔命,四處收賬。在這漫漫征途中,消磨了年初的理想,荒廢了初春的耕種,看盡了世間的冷暖,卻也認(rèn)知了善...
    蓬萊道長(zhǎng)閱讀 317評(píng)論 0 0
  • 作者:趙傳明 嗡嗡,是我外孫的乳名。外孫出生前,女兒女婿就給他起好了這個(gè)好聽的名字。嗡嗡,顧名思...
    戚聿濤閱讀 430評(píng)論 0 6
  • 前言 在不久前看AFNetworking的源碼時(shí)候發(fā)現(xiàn)了這么一句: // 不知道這行代碼的使用場(chǎng)景的同學(xué)你該去自習(xí)...
    李炯7115閱讀 243評(píng)論 0 0

友情鏈接更多精彩內(nèi)容