Angular NgModel Directive Example Tutorial
Okay, let us install Angular using Angular CLI.Step 1: Install Angular using AngularCLI
npm install -g @angular/cliNow, import the FormsModule inside the app.module.ts file.
ng new DemongModel
// app.module.ts
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 { }
Step 2: Create the AppData model
Inside src >> app folder, create one file called AppData.ts and add the following code.
export class AppData {So, here we have taken one property called name which is the type of String.
constructor(
public name: String
) {}
}
Now, import this model file inside the app.component.ts file.
import { Component } from '@angular/core';Step 3: Add HTML code
import { AppData } from './AppData';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
data = new AppData('');
}
Okay, so to work two-way data binding correctly with ngModel, we need to write the following code inside the app.component.html file.
<input type="text" class="form-control" id="name"Step 4: Understanding NgModel
required
[(ngModel)]="data.name" />
<p>Hello {{ data.name }}!</p>
If we take a look at the source code, we’ll notice that ngModel comes with a property binding. The property binding [ngModel] takes care of updating the underlying input DOM element. Angular allows the shorthand syntax using [()], also called “Banana in a box”. So after all, it’s an implementation detail of ngModel that enables two-way data binding.
Finally, Angular NgModel Directive Example Tutorial is over.
Good Post Thanks for sharing this blog. Keep on sharing.
ReplyDeleteAngular JS Online training
Angular JS training in hyderabad