Angular
Angular Directives

NgModel

PRO

Before we dive into NgModel, we need to go over some of the key differences in Angular with regard to a View Template. It is important to walk through this section carefully. Although some of the core features (e.g. Two-Way Binding) from Angular have been turned on their head, it’s important to recognize the purposes of some of the new features that you will be using throughout an application lifecycle. Further details about the Template Syntax for Angular can be found through the Basics guide provided by the Angular team at Google.

One-Way and Two-Way Data Binding

Binding properties to your view layer is different within Angular. Let’s take a look at an example of what should look like a proper binding:

<div>{{ content }}</div>

This has a different meaning now in Angular. This now denotes a one-way binding. This means that although we provide the data to the view, it does not bind any changes back to the Component. To do that, we will need the use of the NgModel directive, which looks like so:

<div [(ngModel)]="content"></div>

However, as with Angular, this directive will not work until it has been imported into our component. We do this by importing the FormsModule as follows:

app/app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HeaderComponent } from './shared/index';

@NgModule({
  imports: [BrowserModule, FormsModule],
  declarations: [AppComponent, HeaderComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

You can view a live example of NgModel in the app/app.component.html file:

Now let’s review a very important question that we see very often with understanding NgModel: whats with the braces and parentheses? Well, the braces denote that our element will be provided a value. This actions binds the information to the view/element. Then, the parentheses denote that the data, when changed, should be updated back to the Component. Hence, we retrieve two-way binding.

Two way data binding is often called "banana in a box" because it looks like... a banana in a box: [()]

For more information about data binding, we recommend taking a look at this great tutorial by our friends on the Angular team at Google for Displaying Data on the view.

 

I finished! On to the next tutorial