14.《Angular响应式表单》

一、使用响应式表单

Angular 的响应式表单能让实现响应式编程风格更容易,这种编程风格更倾向于在非 UI 的数据模型(通常接收自服务器)之间显式的管理数据流, 并且用一个 UI 导向的表单模型来保存屏幕上 HTML 控件的状态和值。 响应式表单可以让使用响应式编程模式、测试和校验变得更容易。

响应式表单.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 构造函数接收一个参数,这里是aaa,这个参数用来指定FormControl的初始值,当此FormControl与页面中input关联时,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());

  }

}
运行结果1.png

制作一个响应式的注册表单

//新建响应式的表单注册组件
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>确认密码:<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重构上面的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);
  }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Angular响应式表单相比较模板驱动表单更大操作性、更易测试性。因此,我更推荐这类表单创造方式。 当一个用于修改...
    cipchk阅读 1,237评论 0 2
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AGI阅读 16,009评论 3 119
  • 年关将至,疲于奔命,四处收账。在这漫漫征途中,消磨了年初的理想,荒废了初春的耕种,看尽了世间的冷暖,却也认知了善...
    蓬莱道长阅读 300评论 0 0
  • 作者:赵传明 嗡嗡,是我外孙的乳名。外孙出生前,女儿女婿就给他起好了这个好听的名字。嗡嗡,顾名思...
    戚聿涛阅读 390评论 0 6
  • 前言 在不久前看AFNetworking的源码时候发现了这么一句: // 不知道这行代码的使用场景的同学你该去自习...
    李炯7115阅读 219评论 0 0