Model forms in angular 2 rc5 do not work

I am moving the code from angular beta to version RC5. and I ran into a problem with the forms forms used. Since I have many forms already developed in angular 2 beta. I find it difficult to change forms based on templates to forms based on templates. any help in form migration is much appreciated.

my existing code is like this

profile.ts

import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from '@angular/forms'; import {FormBuilder, FormGroup, FormControl, Validators} from '@angular/forms'; this.firstName = new FormControl(); this.lastName = new FormControl(); this.email = new FormControl(); this.addressLine = new FormControl(); this.postal = new FormControl(); this.postalArea = new FormControl(); this.form = builder.group({ firstName: this.firstName, lastName: this.lastName, email: this.email, addressLine: this.addressLine, postal: this.postal, postalArea: this.postalArea, photo: this.photo }); 

and the template in profile.HTML is as follows

 <form class="form-default" [formGroup]="form"> <input type="text" class="form-control" id="firstName" [(ngModel)]="model.firstName" formControlName="firstName" maxlength="200"> <input type="text" class="form-control" id="lastName" [(ngModel)]="model.lastName" formControlName="lastName" maxlength="200"> <input type="text" class="form-control" id="email" [(ngModel)]="model.username" readonly formControlName="email" maxlength="100"> </form> 

I encountered the following error in the console.

EXCEPTION: Error: not shown (in the promise): EXCEPTION: error in / assets / scripts / my -profile / my-profile.html: 176: 66 ORIGINAL EXCLUSION: ngModel cannot be used to register form controls using the groupGroup parent directive . Try using the formGroup 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 standalone in ngModelOptions: Example: <div [formGroup]="myGroup"> <input formControlName="firstName"> <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}"> </div> 
+5
source share
2 answers

Here you can find the answer to the same problem : just add:

 [ngModelOptions]="{standalone: true}" 
+5
source

in order to have both ngModel and formControl in your html, you must have a model in your component (for example, firstName in the following example) that you are contacting with your html, and you also need to create a form group, including the desired formControl (for example , firstNameControl in the following example)

component:

  this.firstName: string; this.form = builder.group({ firstNameControl: this.firstName, }); 

HTML

 <form [formGroup]="form"> <input type="text" [(ngModel)]="firstName" [formControl]="form.controls.firstNameControl"></input> </form 
-1
source

All Articles