ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Angular响应式表单

2021-02-18 08:34:27  阅读:255  来源: 互联网

标签:FormControl form required email 响应 Validators 表单 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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有