<tutorialjinni.com/>

Angular ngModel Example Input

In continuation from our last angular tutorial. In this tutorial we explore how modules are added in angular project. We will make a text filed and a simple paragraph tag. Whatever will be written in the text filed will automatically shown in the paragraph tag, in short we will bind text filed with paragraph tag. For that Open app.component.html and replace the entire code with this
<div style="text-align:center">
  <table>
    <tr>
      <td>
        What you write here: <input type="text" [(ngModel)]="typeWriter" />
      </td>
      <td>
        <p>Will display here:  <b>{{ typeWriter }}</b></p>
      </td>
    </tr>
  </table>
</div>
Notice [(ngModel)] it is called Angular Directive, its value is the variable in {{ typeWriter }}. We also need to define this variable in app.component.ts file.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  typeWriter = '';
}
Now if you save this and run this you will encounter and error in chrome developer console Can't bind to 'ngModel' since it isn't a known property of 'input'. It is because Angular does not understand [(ngModel)] yet.

Can't bind to 'ngModel' since it isn't a known property of 'input' Angular is actually split up into multiple modules. We need to add them if you want to use a certain feature from them. For that open app.module.ts and replace it with this
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
The line import {FormsModule} from '@angular/forms'; tell Typescript interpreter where it should look for [(ngModel)]. and FormsModule tells angular to load FormModule too. Once you are done save them open brower and type something. Once you get the hand of it these features are pretty handy. Sample illustration.

ngModel Data Binding
© Tutorial Jinni