Angular Binding in 2 Minutes

There are four ways, we can do data/event binding in angular.



Above diagram shows direction of data from Component to DOM and vice a versa. Note the arrow styles difference. Use [] brackets for property binding denoted by line arrow.

For Event binding use () brackets, which is denoted by angular arrow shape so that  you can remember easily.



In a nutshell the data direction is shown in above figure.
1. Interpolation:


<img src="{{imgUrl}}"/>

imgUrl = 'https://s3.amazonaws.com/coursetro/posts/58-full.png';


Gets translated to property binding.

When to use?  - adding dynamic values between headings

2. Property Binding:

        - It's a one way binding.

Examples

       1.   <app-hero-detail [hero]=“selectedHero"></app-hero-detail>

    2. <h2 [textContent]="title"><h2>


    3. <img [src]="imgUrl"/>

There are 2 variations of property binding.

a. class binding

           You can change the class of the DOM element as below.

         <button class='btn btn-primary' [class.active]="isActive">Save</button>

b. style binding

           You can change the style of the DOM element as below.


    <button class='btn btn-primary'  [style.color]=" isActive==true? 'blue':'red'">Reset</button>

3. Event Binding:

        <li (click)=“save($event)"></li>

$event - an object represents event details, can be verified from console.

event bubbling - event bubbles up dom tree.

Use $event.stopPropagation() stops even bubbling.

Event filtering:

old way:
                 if ($event.keyCode)=13){}

angular way:
                 <input (keyup.enter)="handleEvent($event)"/>

Template variables:
old way:

                console.log($event.target.value)

        angular way:

        Book Name:<input #bookName (keyup.enter)="printBookName(bookName.value)"/>


4. Two-way Binding:


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

Remember syntax using banana-in-a box where square brackets [] represent box and angular brackets () represent banana. 



No comments:

Post a Comment

Calculating Server Capacity: A Comprehensive Tutorial

 In this tutorial we will explore the process of calculating server capacity. Let's get started. Understanding Server Capacity Identifyi...