[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.
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: