unable to create a nested Reactive Form

六眼飞鱼酱① 提交于 2019-12-11 15:41:13

问题


The code/demo is at https://stackblitz.com/edit/angular-jx7fdu

I am trying to create a nested Reactive Form. It is a simple signup form. It has Firstname, Lastname, email, Password and VerifyPassword Field. I have also created validators for the fields. The html also assigns Bootstrap's classes depending on whether a field has errors or not.

<input id="firstname" type="text" class="form-control" formControlName="firstName" [ngClass]="validateField(signupForm,'firstName')" >
      <app-show-errors [control]="signupForm.controls.firstName"></app-show-errors>

validateField in helper.service.ts assigns Bootstraps is-valid and is-invalid classes for visual representation. app-show-errors component gives texttual representation of the error.

For verify password, I want to check that its value is same as that of password field. To do this, I have clubbed them into a FormGroup and am passing that FormGroup to the validator function.

In signup-component.component.ts

    createForm(){ 
        this.signupForm = this.fb.group({
          firstName:[null,[Validators.required,this.helper.validateName]],           lastName:[null,[Validators.required,Validators.pattern(/[A-Za-z]+/)]], 
          email:[null,[Validators.required,Validators.pattern(this.EMAIL_PATTERN)]], 
/*new group for password and verify password. Each of them should match the password criteria and the group should validate that the values of password and verify password is same*/
    passwordGroup:this.fb.group({
            password:[null,[Validators.required,Validators.minLength(8),this.helper.validatePassword]],             confirmPassword:[null,[Validators.required,Validators.minLength(8),this.helper.validatePassword]]
          },{validator:this.helper.confirmPasswordValidator})

        });
      }

Now my main issue is that I am unable to get the nested form (passwordGroup) working. I am seeing the following error in the console.

ERROR Error: formGroup expects a FormGroup instance. Please pass one in.

Example:

<div [formGroup]="myGroup"> <input formControlName="firstName"> </div>

In your class:

this.myGroup = new FormGroup({ firstName: new FormControl() });


回答1:


Change your

<div class="form-group" [formGroup]="passwordGroup">

into

<div class="form-group" formGroupName="passwordGroup">

Nested form groups use formGroupName

You can find more documentation here



来源:https://stackoverflow.com/questions/52051998/unable-to-create-a-nested-reactive-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!