AppDividend
Latest Code Tutorials

Angular NgModel Directive: NgModel in Angular 12

Using the two-way binding, we can display a data property and update that property when that user makes changes. The two-way binding gives components in your app a way to share data.

Using two-way binding, you can listen for events and update values concurrently between parent and child components.

Angular NgModel

Angular NgModel is an inbuilt directive that creates a FormControl instance from the domain model and binds it to a form control element. The ngmodel directive binds the value of HTML controls (input, select, textarea) to application data. 

We can merely achieve it in the component element as well as the HTML element both. The two-way binding uses the syntax as [()] or bind- keyword.

The two-way binding uses the syntax of property binding and event binding together. Property binding uses the syntax as bracket [] or bind- and event binding uses the syntax as the parenthesis () or on- and these bindings are considered one-way binding.

Two-way binding works in both directions are setting the value and fetching the value. The two-way binding uses a specific name pattern.

Okay, let us install Angular using Angular CLI.

Step 1: Install Angular using AngularCLI.

Type the following command to install Angular.

npm install -g @angular/cli

Now, generate the Angular project using the following command.

ng new model

It will create an Angular boilerplate.

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 a file called AppData.ts and add the following code.

// AppData.ts

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.

// app.component.ts

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>
  • For each input tag, we use ngModel directive to bind data with the syntax: [(ngModel)]="data.name" ( AppData is the data model in app.component.ts) class
  • Added a name attribute to the input tag. It is a requirement when using [(ngModel)] in combination with a form.

Save the file and go to the http://localhost:4200

You can see that using the NgModel directive, and we can able do the two-way data binding.

Understanding NgModel

If we 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.

Template variable references

IdentifierUsage
ngModel#myTemplateVar=”ngModel

The FormControl instance tracks a value, the user interaction, and the validation status of the control and keeps the view synced with the model. If used within the parent form, the directive also registers itself with a form as the child control.

This directive is used by itself or as part of the larger form. Use the ngModel selector to activate it.

It accepts the domain model as an optional Input if you have a one-way binding to ngModel with the [] syntax; changing a value of the domain model in the component class sets a value in the view.

If you have the two-way binding with [()] syntax (also known as ‘banana-box syntax’), the value in the UI always syncs back to a domain model in your class.

If we need to inspect the properties of the associated FormControl (like validity state), export the directive into the local template variable using the ngModel as the key (ex: #myVar=”ngModel”).

You then access the control using a directive’s control property, but most properties used (like valid and dirty) fall through to the control anyway for direct access.

Now, first, we need to import the FormsModule inside the app.module.ts file.

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

imports: [
    ...
    FormsModule
  ],

Otherwise, we will get the error like a compiler.js:2175 Uncaught Error: Template parse errors: There is no directive with “exportAs” set to “ngModel”.

Now, write the following code inside the app.component.ts file.

// app.component.ts

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

@Component({
  selector: 'app-root',
  template: `
    <input [(ngModel)]="name" #it="ngModel" required>
    <p>Value: {{ name }}</p>
    <p>Valid: {{ it.valid }}</p>
    <button (click)="setValue()">Set value</button>
  `,
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  name = '';
  setValue() { this.name = 'Millie Bobby Brown'; }
}

Save and go to the browser.

If you press the setValue button, then the following will be the output.

Angular NgModel Example | ngmodel Directive In Angular

When using a ngModel within <form> tags, you will also need to supply the name attribute so that the control can be registered with a parent form under that name.

In the context of the parent form, it’s often unnecessary to include the one-way or two-way binding, as a parent form syncs the value for you.

You can access its properties by exporting them into the local template variable using ngForm (#f=”ngForm“). Use a variable where needed on form submission.

If you need to populate the initial values into your form, using the one-way binding for ngModel tends to be sufficient as long as you use the exported form’s value rather than a domain model’s value on submit.

Using ngModel within the form in Angular

The following example shows controls using ngModel within a form.

import { Component } from '@angular/core';
import {NgForm} from '@angular/forms';
@Component({
  selector: 'app-root',
  template: `
    <form #it="ngForm" (ngSubmit)="onSubmit(it)" novalidate>
      <input name="first" ngModel required #first="ngModel">
      <input name="last" ngModel required #last="ngModel">
      <button>Submit</button>
    </form>
    <p>First name value: {{ first.value }}</p>
    <p>First name valid: {{ first.valid }}</p>
    <p>last name value: {{ last.value }}</p>
    <p>last name valid: {{ last.valid }}</p>
    <p>Form value: {{ it.value | json }}</p>
    <p>Form valid: {{ it.valid }}</p>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  onSubmit(it: NgForm) {
    console.log(it.value);  // { first: '', last: '' }
    console.log(it.valid);  // false
  }
}

 Now, go to the browser and see the magic of the angular ngmodel.

Angular ngmodel not working

If you are a beginner in Angular and working with forms, you often came across an issue like Angular ngmodel not working or two-way data binding is not working as expected.

This issue frequently occurs for newbies in Angular, and to resolve this issue, import the FormsModule in your app.module.ts file. All the form-related functions and properties are defined under the FormsModule.

In addition to FormsModule needed in the imports section of the module declaration in the app.module.ts file, you need to use a form tag or a ngForm directive to enable the ngModel functionalities.

If you use ngModel standalone, without a form somewhere, you don’t have to specify a name for the input, like the following.

<pre class="lang:default decode:true">
 <input ... [(ngModel)]="model.something"`>
</pre>

But when you do use it in a form, the name attribute becomes mandatory.

<form>
  <input ... name="prop" [(ngModel)]="model.prop"`>
</form>

When using the ngModel within tags, you will also need to provide a name attribute so that the control can be registered with the parent form under that name.

Angular ngmodel Methods

#ngOnChanges()

It is a lifecycle method called when the directive’s inputs change for internal use only.

See the following syntax.

ngOnChanges(change: SimpleChanges)

The parameter is called change, an object of key/value pairs for the set of changed inputs.

#ngOnDestroy()

It is a Lifecycle method called before the directive’s instance is destroyed for internal use only.

See the syntax.

ngOnDestroy(): void

There are no parameters.

#viewToModelUpdate()

Sets the new value for the view model and emits a ngModelChange event.

See the syntax.

viewToModelUpdate(newValue: any): void

The function accepts one parameter called newValue, which is the new value emitted by ngModelChange.

Finally, Angular NgModel Example Tutorial is over.

Recommended Posts

Angular NgFor

Angular NgStyle

Angular NgClass

Angular NGXS

Angular NgRx Store

2 Comments
  1. Mario Luiz says

    Tenks,
    This tutorial helps me a lot.

    1. Krunal says

      Your welcome. Keep learning and sharing.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.