Previous Articles:

Introduction To Components And Templates Part 1: Component Metadata

Introduction To Components And Templates Part 2: Templates And Views

Introduction to components and templates Part 3

Without a framework, you would be responsible for pushing data values into the HTML controls and turning user responses into actions and value updates.

Writing such push and pull logic by hand is tedious, error-prone, and a nightmare to read, as any experienced front-end JavaScript programmer can attest.

Angular supports two-way data binding, a mechanism for coordinating the parts of a template with the parts of a component.

Add binding markup to the template HTML to tell Angular how to connect both sides.

The following diagram shows the four forms of data binding markup. Each form has a direction: to the DOM, from the DOM, or both.

This example from the HeroListComponent template uses three of these forms.


//src/app/hero-list.component.html (binding)

<li>{{hero.name}}</li>
<app-hero-detail [hero]="selectedHero"></app-hero-detail>
<li (click)="selectHero(hero)"></li>

1. The {{hero.name}} interpolation displays the component's hero.name property value within the li element.

2. The [hero] property binding passes the value of selectedHero from the parent HeroListComponent to the hero property of the child HeroDetailComponent.

3. The (click) event binding calls the component's selectHero method when the user clicks a hero's name.

Two-way data binding (used mainly in template-driven forms) combines property and event binding in a single notation.

Here's an example from the HeroDetailComponent template that uses two-way data binding with the ngModel directive.


src/app/hero-detail.component.html (ngModel)

<input [(ngModel)]="hero.name">

In two-way binding, a data property value flows to the input box from the component as with property binding.

The user's changes also flow back to the component, resetting the property to the latest value, as with event binding.

enlightened Angular processes all data bindings once for each JavaScript event cycle, from the root of the application component tree through all child components.

Recall this diagram from the post A Complete Diagram With Building Blocks Of An Angular Application

enlightened Data binding plays an important role in communication between a template and its component, and is also important for communication between parent and child components.

Next article:

Introduction To Components And Templates Part 4: Pipes And Directives

Credit: https://angular.io/guide/architecture-components

0 Comments

Leave a reply

Your email address will not be published. required fields are marked *