[Angular2 Form] Nested formGroup, and usage of formGroupName

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:

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