Angular6-模型驱动表单
2019-06-09 本文已影响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;
}
}