Thursday, October 3, 2019

Angular NgModel Directive Example Tutorial

Angular NgModel Directive Example Tutorial

Okay, let us install Angular using Angular CLI.
Angular NgModel Directive Example Tutorial

Step 1: Install Angular using AngularCLI
npm install -g @angular/cli
ng new DemongModel
Now, import the FormsModule inside the app.module.ts file.

// 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 {
  constructor(
      public name: String
  ) {}
}
So, here we have taken one property called name which is the type of String.

Now, import this model file inside the app.component.ts file.
import { Component } from '@angular/core';
import { AppData } from './AppData';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  data = new AppData('');
}
Step 3: Add HTML code
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"
  required
  [(ngModel)]="data.name" />
<p>Hello {{ data.name }}!</p>
Step 4: Understanding NgModel
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.

1 comment: