无法创建嵌套的反应式表单 [英] unable to create a nested Reactive Form

查看:61
本文介绍了无法创建嵌套的反应式表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码/演示位于 https://stackblitz.com/edit/angular-jx7fdu

我正在尝试创建一个嵌套的反应形式.这是一个简单的注册表格.它具有FirstnameLastnameemailPasswordVerifyPassword字段.我还为这些字段创建了验证器. html还会根据字段是否有错误来分配Bootstrapclasses.

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>

helper.service.ts中的

validateField为视觉表示分配Bootstraps is-validis-invalid类. 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.

对于verify password,我要检查其值是否与password字段的值相同.为此,我将它们组合成一个FormGroup并将该FormGroup传递给验证器函数.

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.

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})

        });
      }

现在我的主要问题是我无法使嵌套表单(passwordGroup)工作.我在控制台中看到以下错误.

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() });

推荐答案

更改您的

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

进入

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

嵌套表单组使用formGroupName

Nested form groups use formGroupName

您可以在此处

这篇关于无法创建嵌套的反应式表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆