中安拓也のブログ

プログラミングについて書くブログ

【Angular】エラー: Can't bind to 'ngModel' since it isn't a known property of 'input'.

Angularでフォームを書いていたら、Can't bind to 'ngModel' since it isn't a known property of 'input'.というエラーに遭遇した

バージョン情報

  • Angular: 5.2.9

  • Node: 8.1.4

エラー原因

formControlを使っているのに、NgModuleReactiveFormsModuleをインポートしていないのが原因だった。

src/app/app.module.ts:

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

// ...省略

@NgModule({
  declarations: [AppComponent, ExchangeListComponent, PrivateComponent],
  imports: [
    MatFormFieldModule,
    MatIconModule,
    FormsModule,
    // add this!
    ReactiveFormsModule,
    RouterModule.forRoot(myRoutes)
  ],
// ...省略

下記の手順を実行するとエラーが消える

  1. import { ReactiveFormsModule } from '@angular/forms';ReactiveFormsModuleをインポート

  2. @NgModuleデコレータで定義されているimports:[]リストにReactiveFormsModuleを追加する

エラーメッセージ全文

compiler.js:485 Uncaught Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'input'. (" #loginForm="ngForm">
      <mat-form-field>
        <input matInput placeholder="API Key" id="key" [ERROR ->][(ngModel)]="keySet.key" name="key" [formControl]="key" required>
        <mat-error *ngIf="key.inval"): ng:///AppModule/PrivateComponent.html@7:55
Can't bind to 'formControl' since it isn't a known property of 'input'. ("m-field>
        <input matInput placeholder="API Key" id="key" [(ngModel)]="keySet.key" name="key" [ERROR ->][formControl]="key" required>
        <mat-error *ngIf="key.invalid">{{getErrorMessage()}}</mat-error"): ng:///AppModule/PrivateComponent.html@7:91
No provider for NgControl ("form (ngSubmit)="onSubmit()" class="login-form" #loginForm="ngForm">
      <mat-form-field>
        [ERROR ->]<input matInput placeholder="API Key" id="key" [(ngModel)]="keySet.key" name="key" [formControl]="key"): ng:///AppModule/PrivateComponent.html@7:8
    at syntaxError (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:706:34)
    at TemplateParser.parse (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:24889:19)
    at JitCompiler._parseTemplate (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:34842:37)
    at JitCompiler._compileTemplate (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:34817:23)
    at eval (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:34718:62)
    at Set.forEach (native)
    at JitCompiler._compileComponents (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:34718:19)
    at eval (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:34588:19)
    at Object.then (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:695:77)
    at JitCompiler._compileModuleAndComponents (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:34587:26)

参考サイト

Angular