What is ngModel in Angular?

ngModel provides us the mechanism to sync input data/data from any source (like Web API, Database) from HTML control element to the component class.

Understand this in the very easy way:

Suppose you have a user class named with User as following:

export class User {
id: number;
email: string;
constructor(values: Object = {}) {
//Constructor initialization
Object.assign(this, values);
}
}

And in HTML, you have a textbox for binding email property of the user class.

For simplicity, we will call User class to "U" and textbox control to "T".

 So here are the following definitions:

ngModel provides the way of binding data from U to T and/or vice-versa.

[ngModel]="user.email" is the syntax for one-way binding, while,
[(ngModel)]="user.email" is for two-way binding, and the syntax is compound from
[ngModel]="user.email" and (ngModelChange)="user.email = $event"

If you only need to pass the model, use the first one. If your model needs to listen to change events (e.g. when input field value changes), use the second one.

It's quite simple [] => component to template () => template to component [(ngModel)] is a contracted form of [ngModel]="currentHero.name" (ngModelChange)="currentHero.name=$event">


Comments

  1. Thank you for giving this useful information in this article. It's a fantastic article. I'll be waiting for your next update. I also have some useful information about the Best Custom Software Development Company in India, which I believe will be of great use to you.

    ReplyDelete
  2. Find WordPress Developers in Delhi that are available for hire for your job. Outsource your WordPress jobs to a Freelancer and save.

    ReplyDelete

Post a Comment

Popular posts from this blog

What is unqork?

What is single page Application in web applications

What is SOLID Principle ?