Monday, November 28, 2016

Angular 2 Part 4.3 - Two-way Binding

In Part 4.3, I am going to introduce two-way binding where value keeps in sync in Javascript and HTML.

In our car part example, I am going to add a text field for quantity. User can fill up a quantity or click on plus / minus button to purchase. The value in the text field and buttons is in sync.

...
<input type="text" [(ngModel)]="carPart.quantity">
...
We import FormsModule in main.ts.

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

@NgModule ({
  imports:      [ BrowserModule, FormsModule], // List down all component will be used.
  declarations: [ AppComponent, CarPartComponent], // Import dependencies.
  bootstrap:    [ AppComponent ], // Indicate first component to launch.
  providers:  [RacingDataService] // Now all subcomponents can ask for (inject) our RacingDataService.
})
...

ngModel allows having one command to express two-way data binding. The syntax for two-way binding is [()], and sometimes called banana in a box.

Important to know when we are using ngModel syntax, we only set it equal to a data properly. Example:

[(ngModel)] = "user.age"
[(ngModel)] = "firstname"

You can not set ngModel to a component's method. Example:

[(ngModel)] = "fullname()"

Two-way binding means that if the component property is modified inside the component (Javascript) or inside our web page (HTML), it will stay in sync.

To summary on binding syntax:
  • [] - JavaScript to HTML binding
  • () - HTML to Javascript binding
  • [()] - Two-way binding binding.

No comments:

Post a Comment