码迷,mamicode.com
首页 > 其他好文 > 详细

[Angular2 Form] Nested formGroup, and usage of formGroupName

时间:2016-11-01 07:37:53      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:技术分享   function   form   height   pass   for   abstract   ted   upn   

We can nest formGorup:

    this.reactiveForm = fb.group({
      username: [
        ‘‘,
        [
          Validators.required,
          Validators.minLength(3)
        ]
      ],
      pwds: fb.group({
        pwd: ‘‘,
        rpwd: ‘‘
      }, {validator: passwordValidator})
    });

We make password as an own group. So in html, we need to use formGroupName istead of formControlName.

<form [formGroup]="reactiveForm" novalidate autocomplete="off">
  <div class="form-field">
    <label>Username:</label>
    <input formControlName="username">
    <div class="field-error-message" *ngIf="reactiveForm.controls.title.errors?.required">
      Username is required
    </div>
  </div>

  <div formGroupName="pwds">
    <div class="form-field">
      <label>pwd</label>
      <input formControlName="pwd">
    </div>
    <div class="form-field">
      <label>rpwd</label>
      <input formControlName="rpwd">
    </div>
  </div>
</form>

And how we check the value or errors?:

<pre>
  {{reactiveForm.get(‘pwds‘)?.value | json}}
  {{reactiveForm.get(‘pwds‘)?.errors | json}}
</pre>

 

And we also passwordValidator haven‘t cover yet, it is just a fucntion:

function passwordValidator(c: AbstractControl){
  return c.get(pwd).value === c.get(rpwd).value ?
    null : // valid
    { //invalid
      nomatch: true
    }
}

And notice that we put this validator inside the nested group, so we can get nice error effect:

技术分享

[Angular2 Form] Nested formGroup, and usage of formGroupName

标签:技术分享   function   form   height   pass   for   abstract   ted   upn   

原文地址:http://www.cnblogs.com/Answer1215/p/6018120.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!