Angular6-模型驱动表单

Angular中FormArray写法模板:

html中

Address

Address Value: {{ address.value | json}}

customerForm Value: {{ customerForm.value | json}}

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);
  }

}


那么怎么做字段校验呢

支持字母、数字、下划线,最长10个字符!

支持字母、数字、下划线,最长10个字符!

填写true或false,不区分大小写!

Address

支持字母、数字、下划线或中文,最长20个字符!

支持字母、数字、下划线或中文,最长20个字符!

支持字母、数字、下划线或中文,最长20个字符!

Address Value: {{ address.value | json}}

customerForm Value: {{ customerForm.value | json}}

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;
            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-模型驱动表单)