ngModel cannot be used to register form controls with a parent formGroup directive

前端 未结 10 2018
猫巷女王i
猫巷女王i 2020-12-04 17:21

After upgrading to RC5 we began getting this error:

ngModel cannot be used to register form controls with a parent formGroup 
 directive.
Try using formGroup\         


        
相关标签:
10条回答
  • 2020-12-04 17:59

    If you want to use [formGroup] with formControlName, you must replace name attribute with formControlNameformControlName.

    Example:

    This does not work because it uses the [formGroup] and name attribute.

    <div [formGroup]="myGroup">
       <input name="firstName" [(ngModel)]="firstName">
    </div>
    

    You should replace the name attribute by formControlName and it will work fine like this following:

    <div [formGroup]="myGroup">
       <input formControlName="firstName" [(ngModel)]="firstName">
    </div>
    
    0 讨论(0)
  • 2020-12-04 18:01

    If component has more than 1 form, register all controls and forms

    I needed to know why this was happening in a certain component and not in any other component.

    The issue was that I had 2 forms in one component and the second form didn't yet have [formGroup] and wasn't registered yet since I was still building the forms.

    I went ahead and completed writting both forms complete without leaving a input not registered which solve the issue.

    0 讨论(0)
  • 2020-12-04 18:02

    It looks like you're using ngModel on the same form field as formControlName. Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and will be removed in Angular v7

    0 讨论(0)
  • 2020-12-04 18:06

    I just got this error because I did not enclose all my form controls within a div with a formGroup attribute.

    For example, this will throw an error

    <div [formGroup]='formGroup'>
    </div>
    <input formControlName='userName' />
    

    This can be quite easy to miss if its a particularly long form.

    0 讨论(0)
提交回复
热议问题