1、简单的表单
class Product {
constructor(
public name?: string,
public category?: string,
public price?: number
){ }
}
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent {
newProduct = new Product();
constructor() { }
}
<div>
JSONStringify: {{newProduct | json}}
</div>
<div>
<label>Name:</label>
<input [(ngModel)]="newProduct.name"/>
</div>
<div>
<label>Category:</label>
<input [(ngModel)]="newProduct.category"/>
</div>
<div>
<label>price:</label>
<input [(ngModel)]="newProduct.price"/>
</div>
<button nz-button nzType="primary">Primary</button>
使用ngModel将元素和newProduct对象模型进行绑定
2、添加表单校验
使用HTML元素和属性来定义构成表单的各个域并添加约束校验
JSONStringify: {{newProduct | json}}
<form (ngSubmit)="onSubmit(form)" #form="ngForm" novalidate>
<div>
<label>Name:</label>
<input
[(ngModel)]="newProduct.name"
name="name"
required
minlength="5"
pattern="^[a-zA-Z ]+$"
#name="ngModel"
/>
<ul *ngIf="name.dirty && name.invalid">
<li *ngIf="name.errors.required">
这个是必填项
</li>
<li *ngIf="name.errors.minlength">
至少输入{{name.errors.minlength.requiredLength}}
</li>
<li *ngIf="name.errors.pattern">
只能输入{{name.errors.pattern.requiredPattern}}字符
</li>
</ul>
</div>
<div>
<label>Category:</label>
<input [(ngModel)]="newProduct.category" name="category"/>
</div>
<div>
<label>price:</label>
<input [(ngModel)]="newProduct.price" name="price"/>
</div>
<button type="submit" nz-button nzType="primary">Primary</button>
</form>
input{
outline: none;
}
input.ng-dirty.ng-invalid{
border: 2px solid #ff0000;
}
input.ng-dirty.ng-valid{
border: 2px solid #6bc502;
}
![](https://img.haomeiwen.com/i11094921/2179d83fe3e39f50.png)
input元素和form元素加入css类提供了有关验证状态的详细信息,共有3种验证类。
- ng-dirty 和 ng-pristine
- ng-valid 和 ng-invalid
- ng-touched 和 ng-untouched
这里使用#name="ngModel"
来获取访问器状态。错误信息属性,
- xxx.errors.minlength.requiredLength
- xxx.errors.minlength.actualLength
- xxx.errors.pattern.requiredPattern
- xxx.errors.pattern.actualValue
3、基于模型的表单
基于模型的表单功能在一个名的ReactiveFormsModule的模块中定义
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, NgForm, Validators } from '@angular/forms';
class ProductFormControl extends FormControl{
label: string;
modelProperty: string;
constructor(
label: string,
property: string,
value: any,
validattor: any
){
super(value, validattor);
this.label = label;
this.modelProperty = property;
}
}
@Component({
selector: 'app-form2',
templateUrl: './form3.component.html',
styleUrls: ['./form2.component.css']
})
export class Form2Component implements OnInit {
formGroup: FormGroup;
constructor(public fb: FormBuilder) {
this.formGroup = this.fb.group({
name: new ProductFormControl('Name','name', '', [
Validators.required,
Validators.minLength(5),
Validators.pattern("^[a-zA-Z ]+$")
]),
category: new ProductFormControl('Category','category', '', [Validators.required]),
price: new ProductFormControl('Price','price', '', [
Validators.pattern("^[\\d]+$")
]),
});
console.log(this.formGroup.get('name'))
}
ngOnInit() {}
onSubmit(){}
getControls(){
return Object.keys(this.formGroup.controls).map(k =>
this.formGroup.controls[k] as ProductFormControl
);
}
getValidatorMsgs(control: FormControl){
let message: string[] = [];
if(control.errors){
Object.keys(control.errors).forEach(errorName => {
switch(errorName){
case 'required':
message.push('此项为必填');
break;
case 'minlength':
message.push('最小长度为' + control.errors.minlength.requiredLength);
break;
case 'pattern':
message.push('只能输入' + control.errors.pattern.requiredPattern);
break;
default:
break;
}
})
}
return message;
}
}
JSONStringify: {{ formGroup.getRawValue()| json}}
<form (ngSubmit)="onSubmit()" novalidate [formGroup]="formGroup">
<div *ngFor="let control of getControls()">
<label>{{control.label}}</label>
<input
name="{{control.modelProperty}}"
formControlName="{{control.modelProperty}}"
/>
<ul *ngIf="control.dirty && control.invalid">
<li *ngFor="let error of getValidatorMsgs(control)">
{{error}}
</li>
</ul>
</div>
<button type="submit" nz-button nzType="primary">Primary</button>
</form>
错误信息统一在getValidatorMsgs方法中处理。formGroup.controls是一个object所以使用getControls方法去获取所以的controls。
4、自定义校验规则
新增limit.formvalidator.ts文件
import { FormControl } from '@angular/forms';
export class LimitValidator{
static Limit(limit: number){
return (control: FormControl)=> {
let val = Number(control.value);
if(val != NaN && val > limit){
return {limit: {limit, actualValue: val}}
} else {
return null;
}
}
}
}
...
price: new ProductFormControl('Price','price', '', [
Validators.pattern("^[\\d]+$"),
LimitValidator.Limit(100)
]),
...
...
case 'limit':
message.push('不能大于' + control.errors.limit.limit);
break;
...
网友评论