资讯专栏INFORMATION COLUMN

angular5 Reactive Form动态表单

MorePainMoreGain / 2227人阅读

摘要:根据最近的使用总结一下在中使用创建表单需求创建一个带验证的表单如果表单验证不通过则提交按钮自定义验证器需求密码需要格式为数字字母下划线位参考自定义密码验证通过验证时需要返回密码格式为数字字母下划线位动态创建表单需求表单增

Angular5 Reactive Form

根据最近的使用, 总结一下在ngx中使用reactive form

1. 创建表单

需求: 创建一个带验证的表单, 如果表单验证不通过则提交按钮disabled=true



// app.component.ts

import {Component, OnInit} from "@angular/core";
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  name = "app";

  form: FormGroup;

  constructor(
    private fb: FormBuilder
  ){}

  ngOnInit(){
    this.form = this.fb.group({
      name: ["", Validators.required],
      password: ["", [Validators.required, Validators.minLength(6)]]
    });
  }

  submit(){
    if(this.form.valid){
      console.log("submiting...")
    }else{
      console.log("form is not valid")
    }
  }

  reset(){
    this.form.reset();
  }
}
2. 自定义验证器

需求: 密码需要格式为数字字母下划线6-12位

参考: Custom validators

// app.component.ts

...

// 自定义密码验证
function ValidPwd(control: AbstractControl):any {
  const reg = /^w{6,12}$/;
  if(reg.test(control.value)){
    // 通过验证时需要返回 null
    return null;
  }
  return {status: "error", message: "密码格式为数字字母下划线6-12位"}
}

...
export class AppComponent implements OnInit {
...
  ngOnInit(){
    this.form = this.fb.group({
      name: ["", Validators.required],
      password: ["", [Validators.required, ValidPwd]]
    });
  }
...
}
3. 动态创建表单

需求: 表单增加朋友选项, 默认显示一个, 可以增加/删除



+ -
// app.component.ts

...

export class AppComponent implements OnInit {
  name = "app";

  form: FormGroup;
  friends;

  constructor(
    private fb: FormBuilder
  ) {}

  ngOnInit() {
    this.form = this.fb.group({
      name: ["", Validators.required],
      password: ["", [Validators.required, ValidPwd]],
      friends: this.fb.array([this.createFriend()])
    });

    this.friends = this.form.get("friends") as FormArray;
  }

  /**
   * 动态创建表单
   * @returns {FormControl}
   */
  createFriend() {
    return this.fb.control("", Validators.required);
  }

  /**
   * 增加输入框
   */
  addFriend(): void {
    this.friends.push(this.createFriend());

  }

  /**
   * 移除输入框
   * @param {number} i
   */
  removeFriend(i: number): void {
    this.friends.removeAt(i);
  }

...

}

4. standalone

需求: 增加单选框控制表单

在Reactive表单中, 使用ngModel时, 会出现报错

Error: 
      ngModel cannot be used to register form controls with a parent formGroup directive.

报错中也提示了, 应该在input中增加[ngModelOptions]="{standalone: true}"

文档中是这么介绍的:

standalone: Defaults to false. If this is set to true, the ngModel will not register itself with its parent form, and will act as if it"s not in the form. This can be handy if you have form meta-controls, a.k.a. form elements nested in the 
tag that control the display of the form, but don"t contain form data.

现在表单变成这样:





  
+ -
mobile  landLine

app.componen.ts中增加contactType变量, 表单实例中增加contact:

// app.component.ts

...

export class AppComponent implements OnInit {
  name = "app";

  form: FormGroup;
  friends;
  contactType:number = 0;

  constructor(
    private fb: FormBuilder
  ) {}

  ngOnInit() {
    this.form = this.fb.group({
      name: ["", Validators.required],
      password: ["", [Validators.required, ValidPwd]],
      friends: this.fb.array([this.createFriend()]),
      contact: ["", Validators.required]
    });

    this.friends = this.form.get("friends") as FormArray;
  }

  /**
   * 动态创建表单
   * @returns {FormControl}
   */
  createFriend() {
    return this.fb.control("", Validators.required);
  }

  /**
   * 增加输入框
   */
  addFriend(): void {
    this.friends.push(this.createFriend());

  }

  /**
   * 移除输入框
   * @param {number} i
   */
  removeFriend(i: number): void {
    this.friends.removeAt(i);
  }

  submit() {
    if (this.form.valid) {
      console.log("submitting...");
    } else {
      console.log("form is not valid");
    }
  }

  reset() {
    this.form.reset();
  }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/94617.html

相关文章

  • Java11 HttpClient小试牛刀

    序 本文主要研究一下Java11的HttpClient的基本使用。 变化 从java9的jdk.incubator.httpclient模块迁移到java.net.http模块,包名由jdk.incubator.http改为java.net.http 原来的诸如HttpResponse.BodyHandler.asString()方法变更为HttpResponse.BodyHandlers.of...

    Bmob 评论0 收藏0
  • Java Reactive Web设计与实现

    摘要:概念响应式编程,异步非阻塞就是响应式编程,与之相对应的是命令式编程。的另外一种实现方式就是消息队列。非阻塞设计利用规范中的实现实现代码链接 注: 本文是由读者观看小马哥公开课视频过程中的笔记整理而成。更多Spring Framework文章可参看笔者个人github: spring-framework-lesson 。 0. 编程模型与并发模型 Spring 5实现了一部分Reacti...

    siberiawolf 评论0 收藏0
  • 动态生成form表单,不再为表单烦恼

    摘要:具有数据收集校验和提交功能的表单生成器,支持双向数据绑定和事件扩展,组件包含有复选框单选框输入框下拉选择框等表单元素以及省市区三级联动时间选择日期选择颜色选择滑块评分框架树型文件图片上传等功能组件。 form-create 具有数据收集、校验和提交功能的表单生成器,支持双向数据绑定和事件扩展,组件包含有复选框、单选框、输入框、下拉选择框等表单元素以及省市区三级联动,时间选择,日期选择,...

    kamushin233 评论0 收藏0
  • 使用form-create轻松生成高品质的form表单[附原理图]

    摘要:目的是节省开发人员在表单页面上耗费的时间,从而更专注于功能开发。使用可快速便捷的生成日常开发中所需的各种表单。可通过后端返回生成规则,进行渲染。 form-create 具有动态渲染、数据收集、校验和提交功能的表单生成器,支持双向数据绑定、事件扩展以及自定义组件,可快速生成包含有省市区三级联动、时间选择、日期选择等17种功能组件。 已兼容iview2.和iview3.版本 Github...

    phodal 评论0 收藏0
  • 《Java编程方法论:响应式RxJava与代码设计实战》序

    摘要:原文链接编程方法论响应式与代码设计实战序,来自于微信公众号次灵均阁正文内容在一月的架构和设计趋势报告中,响应式编程和函数式仍旧编列在第一季度的早期采纳者中。 原文链接:《Java编程方法论:响应式RxJava与代码设计实战》序,来自于微信公众号:次灵均阁 正文内容 在《2019 一月的InfoQ 架构和设计趋势报告》1中,响应式编程(Reactive Programming)和函数式...

    PAMPANG 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<