首页 > 其他 > 详细

[Angular2 Form] Nested formGroup, and usage of formGroupName

时间:2016-11-01 07:36:27      阅读:296      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!