Angular响应式表单
作者:互联网
响应式表单也叫模型驱动型表单。
有三个重要元素FormControl,FormGroup和FormBuilder。还有一个FormArray。
验证器和异步验证器。
动态指定验证器。条件改变验证方式改变。
自定义FormControl。用于表单过于复杂之后,逻辑难以理清楚。把复杂问题拆成若干简单问题永远是万能钥匙。
一、登录表单
多个validators:
Validators.compose([Validators.required, Validators.email])返回ValidatorFn。 动态指定validator: 一开始可以不指定validator,在某些条件下动态指定validator: this.form.controls['email'].setValidators(this.validate); 查看errors: <mat-error>{{form.controls['email'].errors | json}}</mat-error> 模板:<form [formGroup]="form" (ngSubmit)="onSubmit(form,$event)"> <mat-card class="example-card"> <mat-card-header> <mat-card-title>登录:</mat-card-title> </mat-card-header> <mat-card-content> <mat-form-field class="example-full-width" class="full-width"> <input type="text" formControlName="email" matInput placeholder="您的email" style="text-align: right"> <mat-error>{{form.controls['email'].errors | json}}</mat-error> </mat-form-field> <mat-form-field class="example-full-width" class="full-width"> <input type="password" formControlName="password" matInput placeholder="您的密码" style="text-align: right"> </mat-form-field> <button mat-raised-button type="submit" color="primary" [disabled]="!form.valid">登录</button> </mat-card-content> <mat-card-actions class="text-right"> <p>还没有账户?<a routerLink="/register">注册</a></p> <p>忘记密码?<a href="">找回</a></p> </mat-card-actions> </mat-card> <mat-card class="example-card"> <mat-card-header> <mat-card-title>每日佳句</mat-card-title> <mat-card-subtitle>满足感在于不断的努力,而不是现有成就。全心努力定会胜利满满。</mat-card-subtitle> </mat-card-header> <img mat-card-image src="/assets/images/quote_fallback.jpg" alt=""> <mat-card-content> Satisfaction lies in the effort, not in the attainment. Full effort is full victory. </mat-card-content> </mat-card> </form>View Code
组件:
export class LoginComponent implements OnInit { form: FormGroup; constructor(private fb: FormBuilder) { // this.form = new FormGroup({ // email: new FormControl("wang@163.com", Validators.compose([Validators.required, Validators.email])), // password: new FormControl("",Validators.required), // }) //formBuilder不需要显示的new FormControl this.form = this.fb.group({ email: ["wang@163.com", Validators.compose([Validators.required, Validators.email, this.validate]) ], password:["",Validators.required] }) } ngOnInit(): void { } onSubmit(form: FormGroup, event: Event) { event.preventDefault(); console.log(JSON.stringify(form.value)); console.log(form.valid); } validate(c:FormControl):{[key:string]:any} | null{ if(!c.value){ return null; } const pattern=/^wang+/; if(pattern.test(c.value)){ return null; }else{ return { emailNotValid: 'The email must start with wang' } } } }View Code
二、封装自定义表单控件
把注册表单中的图片列表抽成一个独立组件。
ng g c shared/image-list-select生成组件
- 实现ControlValueAccessor接口。实现writeValue(),registerOnChange()和registerOnTouched()
- 定义一个providers,令牌NG_VALUE_ACCESSOR和NG_VALIDATORS。用useExisting加forwardRef。并且设置multi为true。
2019-04-07
标签:FormControl,form,required,email,响应,Validators,表单,Angular 来源: https://www.cnblogs.com/starof/p/10666517.html