美文网首页
Angular6-模型驱动表单

Angular6-模型驱动表单

作者: 月上秦少 | 来源:发表于2019-06-09 14:24 被阅读0次

Angular中FormArray写法模板:

html中

<form [formGroup]="customerForm">
  <label for="id">id:
    <input type="number" formControlName="id" id="id">
  </label>
  
  <label for="name">name:
    <input type="text" formControlName="name" id="name">
  </label>
  
  <label for="isVip">isVip:
    <input type="text" formControlName="isVip" id="isVip">
  </label>
  
  <button (click)="add()">Add</button>
  
  <div formArrayName="address">
    <h3>Address</h3>
    <button (click)="addAddress()">Add address</button>
    
    <div *ngFor="let address of address.controls; let i=index">
      <div [formGroupName]="i"> <!--此处必须为index值-->
        <label>
          Street:
          <input type="text" formControlName="street"> <!--此处必须为key值-->
        </label>
  
        <label>
          City:
          <input type="text" formControlName="city"> <!--此处必须为key值-->
        </label>
  
        <label>
          State:
          <input type="text" formControlName="state"> <!--此处必须为key值-->
        </label>
      </div>
    </div>
  </div>
  
  <p>
    Address Value: {{ address.value | json}}
  </p>
  <p>
    customerForm Value: {{ customerForm.value | json}}
  </p>
</form>

ts文件

import {Component, OnInit} from '@angular/core';
import {Customer} from './customer-interface';
import {CustomerListService} from './customer-list.service';
import {FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'app-customer-list',
  templateUrl: './customer-list.component.html',
  styleUrls: ['./customer-list.component.css']
})
export class CustomerListComponent implements OnInit {
  customers: Customer[];
  customerForm: FormGroup;

  customerFormValue = null;

  constructor(private customerService: CustomerListService, private fb: FormBuilder) {
    this.customers = customerService.getCustomers();
  }

  ngOnInit() {
    this.createForm(); // 初始化创建表单
  }

  createForm() {
    this.customerForm = this.fb.group({
      id: [''],
      name: ['', Validators.required],
      isVip: ['', Validators.required],
      address: this.fb.array([
        this.createAddress()
      ])
    });

  }

  createAddress(): FormGroup {
    return this.fb.group({
      street: [],
      city: [],
      state: [],
    });
  }

  get address() {
    return this.customerForm.get('address') as FormArray;
  }

  addAddress(): void {
    this.address.push(this.createAddress());
  }

  add() {
    const newCustomer = {
      id: this.customerForm.value.id,
      isVip: this.customerForm.value.isVip,
      name: this.customerForm.value.name
    };
    this.customers.push(newCustomer);
    this.customerFormValue = this.customerForm.value;
    console.log(this.customerFormValue);
  }

}


那么怎么做字段校验呢

<form [formGroup]="customerForm">
  <label for="id">id:
    <input type="number" formControlName="id" id="id">
  </label>
  <p *ngIf="checkFiled('id')" style="color: red;">支持字母、数字、下划线,最长10个字符!</p>
  
  <label for="name">name:
    <input type="text" formControlName="name" id="name">
  </label>
  <p *ngIf="checkFiled('name')" style="color: red;">支持字母、数字、下划线,最长10个字符!</p>
    
  <label for="isVip">isVip:
    <input type="text" formControlName="isVip" id="isVip">
  </label>
  <p *ngIf="checkFiled('isVip')" style="color: red;">填写true或false,不区分大小写!</p>
  
  <button (click)="add()">Add</button>
  
  <div formArrayName="address">
    <h3>Address</h3>
    <button (click)="addAddress()">Add address</button>
    
    <div *ngFor="let address of address.controls; let i=index">
      <div [formGroupName]="i"> <!--此处必须为index值-->
        <label>
          Street:
          <input type="text" formControlName="street"> <!--此处必须为key值-->
        </label>
            <p *ngIf="checkFiled('street', i)" style="color: red;">支持字母、数字、下划线或中文,最长20个字符!</p>
            
        <label>
          City:
          <input type="text" formControlName="city"> <!--此处必须为key值-->
        </label>
            <p *ngIf="checkFiled('city', i)" style="color: red;">支持字母、数字、下划线或中文,最长20个字符!</p>
            
        <label>
          State:
          <input type="text" formControlName="state"> <!--此处必须为key值-->
        </label>
        <p *ngIf="checkFiled('state', i)" style="color: red;">支持字母、数字、下划线或中文,最长20个字符!</p>
      </div>
    </div>
  </div>
  
  <p>
    Address Value: {{ address.value | json}}
  </p>
  <p>
    customerForm Value: {{ customerForm.value | json}}
  </p>
</form>

 <button (click)="submit()">submit</button>

ts文件

import {Component, OnInit} from '@angular/core';
import {Customer} from './customer-interface';
import {CustomerListService} from './customer-list.service';
import {FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'app-customer-list',
  templateUrl: './customer-list.component.html',
  styleUrls: ['./customer-list.component.css']
})
export class CustomerListComponent implements OnInit {
  customers: Customer[];
  customerForm: FormGroup;

  customerFormValue = null;

  constructor(private customerService: CustomerListService, private fb: FormBuilder) {
    this.customers = customerService.getCustomers();
  }

  ngOnInit() {
    this.createForm(); // 初始化创建表单
  }

  createForm() {
    this.customerForm = this.fb.group({
      id: [null, [Validators.required, Validators.maxLength(10), Validators.pattern(/^[a-zA-Z0-9_]+$/)]],
      name: [null, [Validators.required, Validators.maxLength(10), Validators.pattern(/^[a-zA-Z0-9_]+$/)]],
      isVip: [null,  [Validators.required, Validators.pattern(/^(true)|(false)$/i)]],
      address: this.fb.array([
        this.createAddress()
      ])
    });

  }

  createAddress(): FormGroup {
    return this.fb.group({
      street: [null, [Validators.required, Validators.maxLength(20), Validators.pattern(/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/)]],
      city: [null, [Validators.required, Validators.maxLength(20), Validators.pattern(/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/)]],
      state: [null, [Validators.required, Validators.maxLength(20), Validators.pattern(/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/)]],
    });
  }

  get address() {
    return this.customerForm.get('address') as FormArray;
  }

  addAddress(): void {
    this.address.push(this.createAddress());
  }

  add() {
    const newCustomer = {
      id: this.customerForm.value.id,
      isVip: this.customerForm.value.isVip,
      name: this.customerForm.value.name
    };
    this.customers.push(newCustomer);
    this.customerFormValue = this.customerForm.value;
    console.log(this.customerFormValue);
  }
  
  // 检验字段合法性
    checkFiled(filed: string, i=-1): Boolean {
        if(i > -1){ // 校验address字段
            return this.address.controls[i].get(filed).dirty && this.customerForm.get(filed).errors;
        }else { // 检验其他字段
            return this.customerForm.get(filed).dirty && this.customerForm.get(filed).errors;
        }
    }
  // 确认提交
    submit(){
      //提交前先验证字段是否都通过了校验
      if(verifyForm()){ // verifyForm()返回值为true,字段都通过了校验
          // 提交到后台
      }
    }
    
     //  校验表单信息
     verifyForm(): boolean {
          let flag = true;
          for (const i in this.customerForm.controls) {
              if (this.customerForm.controls[i]) {
                  this.customerForm.controls[i].markAsDirty();
                  this.customerForm.controls[i].updateValueAndValidity();
                  if (null != this.customerForm.controls[i].errors) {
                      flag = false;
                  }
              }
          }
          // 检验address
           this.address.controls.forEach(formGroup => {
            const group: FormGroup = <FormGroup>formGroup;
            for (const c in group.controls) {
                if (group.controls[c]) {
                    group.controls[c].markAsDirty();
                    group.controls[c].markAsTouched();
                    group.controls[c].updateValueAndValidity();
                    if (null != group.controls[c].errors) {
                        flag = false;
                    }
                }
            }
           })
          return flag;
      }
}


相关文章

  • Angular6-模型驱动表单

    Angular中FormArray写法模板: html中 ts文件 那么怎么做字段校验呢 ts文件

  • Angular 表单

    在 Angular 中,表单有两种类型,分别为模板驱动和模型驱动 1. 模板驱动 1.1 概述 表单的控制逻辑...

  • angular 响应式表单和模型驱动表单—angular学习笔记

    响应式表单和模型驱动表单相同与不同之处 相同:两者都从视图中捕获用户输入事件、验证用户输入、创建表单模型、修改数据...

  • 细说 Angular 2+ 的表单(二):响应式表单

    细说 Angular 2+ 的表单(一):模板驱动型表单 响应式表单 响应式表单乍一看还是很像模板驱动型表单的,但...

  • Angular表单创建和校验

    Angular中提供了模板驱动表单和响应式表单。相对来做,模板驱动表单使用更加简单,只需要在表单外围添加#myFo...

  • python 自动化测试五种模型

    python 自动化测试五种模型,线性、模块化驱动模型、数据驱动模型、关键字驱动模型、行为驱动模型 通过录制或编写...

  • angular表单的使用实例

    大纲 1、模板驱动表单的创建2、响应式表单的创建3、模板驱动型表单的自定义指令4、响应式表单的自定义指令5、父组件...

  • Struts2笔记

    Struts2笔记——Struts2的模型驱动(ModelDriven) 1. 模型驱动: 模型驱动是使用...

  • angular表单知识点

    大纲 1、对表单的理解2、模板驱动表单(Template Driven Forms)3、响应式表单(Reactiv...

  • ng-alain表单使用方式

    Angular表单 Angular提供两种不同的架构范式表单:模板驱动和响应式表单,官网也简单实现了动态表单范例。...

网友评论

      本文标题:Angular6-模型驱动表单

      本文链接:https://www.haomeiwen.com/subject/bkegxctx.html