How to bind object property to textbox in angular2

21.5k views Asked by At

I am new to Angular and i am trying to bind the form which consists of text boxes from model object. but i am receiving an error like "Unhandled Promise rejection: Template parse errors:Can't bind to 'NgModel' since it isn't a known property of 'input'"

i had invest lot of time in google but still problem exists

Below are my code.

html:

    <div>
     <div class="col-sm-6 form-group">
        <label class="control-label">Project Name:</label>
        <input type="text" class="form-control" id="txtProjName" [(NgModel)]="projectFieldsdtl.PROJECT_NAME" >
    </div>

     <div class="col-sm-6 form-group">
        <label class="control-label">Project Manager Name:</label>
        <input type="text" class="form-control" id="txtProjManager" >
    </div>
    <div class="col-sm-6 form-group">
        <label class="control-label">Project Manager Email ID:</label>
        <input type="text" class="form-control" id="txtProjManagerMailID" >
    </div>
    </div>

app.module.ts

    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppComponent }  from './app.component';
    import { FormsModule} from '@angular/forms';  
    import { HttpModule } from '@angular/http';
    import {SpotCheckStatusComponent} from './spotcheckstatus.component';

    @NgModule({
      imports:      [ BrowserModule ,FormsModule,HttpModule ],
      declarations: [ AppComponent,SpotCheckStatusComponent ],
      bootstrap:    [ SpotCheckStatusComponent ]
    })
    export class AppModule { }

projectFields.ts

        export class projectFields {
                public PROJECT_CODE:string;
                public PROJECT_NAME:string
                public PROJECT_MANAGER: string;
                public PROJECT_MANAGER_EMAIL_ID: string;    
        }

SpotCheckStatusComponent.ts

            import {Component,OnInit ,OnChanges} from '@angular/core';
        import {IMyDpOptions} from 'mydatepicker';
        import {HttpService} from './http.service';
        import { serviceLine } from './models/serviceLine';  
        import { projectFields } from './models/projectFields';  


        @Component({
          selector: 'my-app',
          styleUrls:['/css/home.css'],
          templateUrl:'./SpotCheckStatus.html',
          providers:[HttpService]

        })
        export class SpotCheckStatusComponent  implements OnInit
        {
             name = 'SpotCheckStatus'; 

             public projectFieldsdtl: projectFields[];  

          constructor(
            private httpService: HttpService
          ) {}

          ngOnInit(){

                  this.httpService.getProjectCode(serviceline).subscribe(
                  response=> {      

                    this.projectFieldsdtl=response[0];
                    },
                  error=> {
                      console.log("ERROR: ",error);
                      console.log(error.json()); //gives the object object
                  },
                  () => {
                      console.log("Completed");
                  }

                  );
            }
        }

And finally projectFieldsdtl got the object as below:

    [{
    PROJECT_CODE:"9999"
    PROJECT_MANAGER:"shekat"
    PROJECT_MANAGER_EMAIL_ID:"[email protected]"
    PROJECT_NAME:"ABFL"
    }]
3

There are 3 answers

4
Ramesh Rajendran On BEST ANSWER

You have missed double quotes in the ngmodel.

<input type="text" class="form-control" id="txtProjName" [(ngModel)]="projectFieldsdtl.PROJECT_NAME" >

EDIT

Also you are using Array object in the ng-model. So it should be like projectFieldsdtl[0].PROJECT_NAME instead of projectFieldsdtl.PROJECT_NAME.

Because of the service aync calling . try this *ngIf=" projectFieldsdtl != null" on your div tag

<div class="col-sm-6 form-group" *ngIf="projectFieldsdtl != null && projectFieldsdtl != undefined">
        <label class="control-label">Project Name:</label>
        <input type="text" class="form-control" id="txtProjName" [(NgModel)]="projectFieldsdtl[0].PROJECT_NAME" >
    </div>

And you should initialize an empty object in nginit function , try this below code

ngOnInit(){
    this.projectFieldsdtl=[{
    PROJECT_CODE:""
    PROJECT_MANAGER:""
    PROJECT_MANAGER_EMAIL_ID:""
    PROJECT_NAME:""
    }];
}
5
masterpreenz On

ngModel is case sensitive so you should put [(ngModel)] not [(ngmodel)].

your second problem is when you received undefined model, it is due to projectFieldsdtl is undefined or contain null value.

in your JS contructor() consider initializing projectFieldsdtl to object.

// make sure to declare it as well
projectFieldsdtl: any;

constructor()
{
  // initialize its value
  this.projectFieldsdtl = {};
}

hope that helps

0
Rohan Fating On

Since you are getting array from service you can do like follow and use [(ngModel)]

    In Component

    public projectFieldsdtl: projectFields = {};  

    Service Response 

    this.projectFieldsdtl=response[0]

    template 

        <input type="text" class="form-control" id="txtProjName" [(ngModel)]="projectFieldsdtl.PROJECT_NAME" >





Another Way to implement

   <div *ngFor='let item of projectFieldsdtl; let i=index'>
                   <input type="text" class="form-control" id="txtProjName_{{i}}" [(ngModel)]="item .PROJECT_NAME" >
                    </div>

   In component 

   public projectFieldsdtl: projectFields[] = [];  

   Service Response 

   this.projectFieldsdtl=response;