您的位置:首页 > 博客中心 > 互联网 >

[Angular2 Form] Nested formGroup, and usage of formGroupName

时间:2022-04-30 20:40

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.

Username is required

And how we check the value or errors?:

  {{reactiveForm.get(‘pwds‘)?.value | json}}
  {{reactiveForm.get(‘pwds‘)?.errors | json}}

 

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:

技术分享

本类排行

今日推荐

热门手游