Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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's partner directive "formControlName" instead.  Example:

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

    In your class:

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

      Or, if you'd like to avoid registering this form control,
 indicate that it's standalone in ngModelOptions:

      Example:

      
  <div [formGroup]="myGroup">
     <input formControlName="firstName">
     <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">
  </div>

It looks like in RC5 the two can no longer be used together, but I could not find an alternative solution.

Here is the component producing the exception:

    <select class="field form-control" [formGroup]="form" [(ngModel)]="cause.id" [name]="name">
    <option *ngFor="let c of causes" [value]="c.text">{{c.text}}</option>
    </select>
like image 948
user2363245 Avatar asked Aug 24 '16 14:08

user2363245


3 Answers

The answer is right on the error message, you need to indicate that it's standalone and therefore it doesn't conflict with the form controls:

[ngModelOptions]="{standalone: true}"
like image 140
Avenir Çokaj Avatar answered Nov 08 '22 02:11

Avenir Çokaj


Expanding on @Avenir Çokaj's answer

Being a novice even I did not understand the error message clearly at first.

What the error message indicates is that in your formGroup you have an element that doesn't get accounted for in your formControl. (Intentionally/Accidentally)

If you intend on not validating this field but still want to use the ngModel on this input element please add the flag to indicate it's a standalone component without a need for validation as mentioned by @Avenir above.

like image 35
saNiks Avatar answered Nov 08 '22 01:11

saNiks


OK, finally got it working: see https://github.com/angular/angular/pull/10314#issuecomment-242218563

In brief, you can no longer use name attribute within a formGroup, and must use formControlName instead

like image 20
user2363245 Avatar answered Nov 08 '22 02:11

user2363245