如何将对象 属性 绑定到 angular2 中的文本框

How to bind object property to textbox in angular2

我是 Angular 的新手,我正在尝试绑定由模型对象中的文本框组成的表单。 但我收到类似 "Unhandled Promise rejection: Template parse errors:Can't bind to 'NgModel' since it isn't a known property of 'input'"

的错误

我在 google 上投入了很多时间,但问题仍然存在

下面是我的代码。

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");
                  }

                  );
            }
        }

最后projectFieldsdtl得到如下对象:

    [{
    PROJECT_CODE:"9999"
    PROJECT_MANAGER:"shekat"
    PROJECT_MANAGER_EMAIL_ID:"teja.ravi@gmal.com"
    PROJECT_NAME:"ABFL"
    }]

您在 ngmodel 中遗漏了双引号。

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

编辑

您还在 ng-model 中使用 Array 对象。所以它应该像 projectFieldsdtl[0].PROJECT_NAME 而不是 projectFieldsdtl.PROJECT_NAME

因为调用 aync 服务。在你的 div 标签

上试试 *ngIf=" projectFieldsdtl != null"
<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>

你应该在 nginit 函数中初始化一个空对象,试试下面的代码

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

ngModel 区分大小写,因此您应该输入 [(ngModel)] 而不是 [(ngmodel)].

您的第二个问题是当您收到 undefined 模型时,这是由于 projectFieldsdtl 未定义或包含 null 值。

在您的 JS contructor() 中考虑初始化 projectFieldsdtl 对象。

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

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

希望对您有所帮助

由于您是从服务中获取数组,因此您可以遵循并使用 [(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;