Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

model based forms in angular 2 rc5 not working

Tags:

I am migrating code from angular beta to RC5 version. and i am facing issue with the model based forms used. As i have to much forms already developed in angular 2 beta. its hard for me to changes model based forms to template based forms. any help in forms migration is highly 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 template in profile.HTML is like 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 am facing following error in console.

EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in /assets/scripts/my-profile/my-profile.html:176:66 ORIGINAL EXCEPTION: 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>
like image 862
sachin kulkarni Avatar asked Sep 01 '16 11:09

sachin kulkarni


1 Answers

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

[ngModelOptions]="{standalone: true}"
like image 61
Avenir Çokaj Avatar answered Sep 24 '22 16:09

Avenir Çokaj