Devlog/Web

[Angular] error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'.

Damien.Lee 2020. 12. 8. 19:19
반응형
 

Angular를 처음 접하시는 분들께서 양방향 바인딩 ( two-way binding ) 에 대해 배우실 때 쯤, ngModel 을 사용하다가 마주치게 될 확률 이 높은 에러 입니다.

문제점

// input-customer.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-input-customer',
  templateUrl: './input-customer.component.html',
  styleUrls: ['./input-customer.component.css']
})
export class InputCustomerComponent implements OnInit {

  public inputName: string;

  constructor() {
    this.inputName = '';
  }

  ngOnInit(): void {
  }
}

코드 작성 후 해당 컴포넌트의 html ( input-customer.component.html ) 에서 input에 ngModel 을 적용시킵니다.

<input type="text" [(ngModel)]="inputName">

그리고 컴파일을 진행하게 되면, 아래와 같은 에러가 발생하게 됩니다.

error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'.

 

 

해결방법

Angular에서 Input 과 같은 Form 에 대한 양방향 바인딩 ( two-way binding ) 을 하기 위해선 FormsModule 을 추가로 Import 해줘야 합니다.
app.module.ts 로 가서 아래와 같이 FormsModule 을 추가해주면 에러는 해결 됩니다.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

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

 

참고자료

- Angular 공식 문서 - Built-in directives
- Angular 공식 문서 - 양방향 바인딩

반응형