未捕获错误:模板解析错误:无法绑定到'ngModel',因为它不是'input'的已知属性

时间:2017-12-07 05:05:00

标签: angular

我正在使用Angular 4.2.4并且我在控制台中收到错误:

Uncaught Error: Template parse errors: Can't bind to 'ngModel' since it isn't a known property of 'input'.

虽然我在文件app.module.ts中包含FormsModule,如

import { FormsModule,ReactiveFormsModule }   from '@angular/forms';
@NgModule({
  declarations: [
    AppComponent,
    ...APP_LAYOUTS,
    ...APP_COMPONENTS,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

和html代码为

<form id="user-add-form">
    <div class="text-center m-t-10"><span class="login-img"><i class="ti-check-box"></i></span></div>
    <h3 class="login-title">Add New User</h3>
    <div class="row">
      <div class="col-6">
        <div class="form-group">
          <input class="form-control" type="text" name="first_name" [(ngModel)]="first_name" placeholder="First Name">
        </div>
      </div>
      <div class="col-6">
        <div class="form-group">
          <input class="form-control" type="text" name="last_name" [(ngModel)]="last_name" placeholder="Last Name">
        </div>
      </div>
    </div>
    <div class="form-group">
      <input class="form-control" type="email" name="email" [(ngModel)]="email" placeholder="Email" autocomplete="off">
    </div>
    <div class="form-group">
      <input class="form-control" id="password" type="password" name="password" [(ngModel)]="password" placeholder="Password">
    </div>
    <div class="form-group">
      <input class="form-control" type="password" name="password_confirmation" [(ngModel)]="password_confirmation" placeholder="Confirm Password">
    </div>
    <div class="form-group">
      <button class="btn btn-info btn-block" type="submit">Submit</button>
    </div>
  </form>

和一些组件文件代码是

import { FormBuilder,Validator } from '@angular/forms';
export class UserAddComponent implements OnInit, OnDestroy, AfterViewInit {
    first_name: string;
    last_name: string;
    email: string;
    password: string;
    password_confirmation: string;

我已经看到以下链接但没有得到任何解决方案

Angular 4 - "Can't bind to 'ngModel' since it isn't a known property of 'input' " error

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

Can't bind to 'ngModel' since it isn't a known property of 'input'

请帮忙解决它

1 个答案:

答案 0 :(得分:7)

来自Wiki,

  

此错误通常表示您尚未声明指令“x”或   没有导入“x”所属的NgModule。

     

如果“x”确实不是属性或者“x”是a,则也会出现此错误   私有组件属性(即缺少@Input或@Output   装饰)。

     

例如,如果“x”是ngModel,则可能没有导入   来自@ angular / forms的FormsModule。

     

也许您在应用程序功能模块中声明了“x”但忘记了   出口呢? “x”类对其他组件不可见   NgModules,直到您将其添加到导出列表

所以只需在'UserAddComponent'中导入'FormsModule'

import { FormsModule,ReactiveFormsModule } from '@angular/forms';

希望它有所帮助!!