快速生成一个表单,需求如下:
收集以下信息:
姓名,字符串,必填
地址,字符串,选填
兴趣,字符串,选填
问题,对象,必填
电话,数组,选填
示例数据:
data = { name: 'zhangming', address: 'China Xian', hobby: 'Sing', questions: { question1: "What's your pet?", answer1: 'dog', question2: 'Where do you want to go?', answer2: 'England' }, tels: ['13282928282','123272837282'] }
需求,如果有数据能快速load到页面,同时页面也给用户编辑,之后能快速取出数据
1. 引用模块
2. 定义表单对象
属性名与数据源的属性名最好一一对应,这样好取数据
3.编写HTML
<form [formGroup]="form" (ngSubmit)="onSubmit()" class="form"> <label> Name: <input formControlName="name" required> </label> <label> Address: <input formControlName="address" [style.width.px]="300"> </label> <label> Hobby: <input formControlName="hobby"> </label> <div formGroupName="questions"> <label> Qusetion1: <input formControlName="question1" required> </label> <label> Answer1: <input formControlName="answer1" required> </label> <label> Qusetion2: <input formControlName="question2" required> </label> <label> Answer2: <input formControlName="answer2" required> </label> </div> <div formArrayName="tels"> Telphone <button (click)="addTel()">+</button> <label *ngFor="let tel of telList.controls;let i = index"> <input [formControlName]="i"> </label> </div> <button (click)="onSubmit()" [disabled]="!form.valid" [style.margin-top.px]="50">submit</button> </form>
注意几个点:
使用:
1. 数据到UI
2. 从UI取数据
运行效果:
简单的数据验证:
1. 使用 Angular 内置的一些校验和 一个自定义校验逻辑
自定义的校验:
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn { return (control: AbstractControl): { [key: string]: any } | null => { const forbidden = nameRe.test(control.value); return forbidden ? { 'forbiddenValue': { value: control.value } } : null; }; }
使用校验,这里对一个控件加了三个校验,前两个是内置,最后一个自定义
ts:
form = this.fb.group({ name: ['', [Validators.required, Validators.minLength(4), forbiddenNameValidator(/^d{4}$/)]], address: [''], hobby: [''], questions: this.fb.group({ question1: ['', Validators.required], answer1: ['', Validators.required], question2: ['', Validators.required], answer2: ['', Validators.required] }), tels: this.fb.array([this.fb.control('')]) });
暴露name这个form control,这样就能在html里引用错误
加之前:
<label> Name: <input formControlName="name" required> </label>
加之后:
<label> Name: <input formControlName="name" required> <ng-container *ngIf="name.invalid && (name.touched || name.dirty)" > <div *ngIf="name.errors.required" class="error"> Name is required. </div> <div *ngIf="name.errors.minlength" class="error"> Name must be at least 4 characters long. </div> <div *ngIf="name.errors.forbiddenValue" class="error"> Name can not be four number. </div> </ng-container> </label>
效果:
刚运行起来,不操作,不显示消息:
点击之后:
输入几个字符:
输入不符合正则表达式:
css:
.error { color: #a94442; }