AppDividend
Latest Code Tutorials

Angular NgModel Example | ngmodel Directive In Angular 9/8/7

0

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. 

Using the two-way binding, we can display a data property as well as an update that property when the user makes changes.

Angular NgModel

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 as 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 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 to do the two-way data binding.

#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.

#Template variable references

IdentifierUsage
ngModel#myTemplateVar=”ngModel

 

The FormControl instance tracks a value, the user interaction, and 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 in need of 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 compiler.js:2175 Uncaught Error: Template parse errors: There is no directive with “exportAs” set to “ngModel”.

Now, write a 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 it into the local template variable using ngForm such as (#f=”ngForm“). Use a variable where needed on form submission.

If you do 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 a 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 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, which is 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 Example

Angular NgStyle Example

Angular NgClass Example

Angular NGXS Example

Angular NgRx Store Example

Leave A Reply

Your email address will not be published.

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