Angular Learning Day 3: Displaying Data and Handling Events
Tags: angular, pipe, binding
Published: 2021-01-03 05:21:20

---
title: Angular Learning Day 3: Displaying Data and Handling Events
published: true
description: 
tags: angular, pipe, binding
//cover_image: https://direct_url_to_image.jpg
---
**Objective**: In this article, you will know **angular property binding**, **attribute binding**, **class binding**, **style binding**, **event binding**, **two-way binding**, **event bubbling**, **event filtering**, **angular pipe**.

**Pre-requisite** Prior to completing this article, you should have already installed all pre-requisite tooling including: Visual Studio Code, Node Package Manager (NPM), Node, Angular CLI.

## Property Binding

`{}` double curly braces uses display data. 

**courses.component.ts**
```
imageUrl = "https://via.placeholder.com/150"
```
**courses.component.html**
```
<img src="{{imageUrl}}" alt="">
```
or 
```
<img [src]="imageUrl" alt="">
```
Interpolation is just a Syntactic sugar. Behind the scene when angular compile a template is translate this interpolation. It we call property binding. 

With property binding we bind DOM element like `src="{{imageUrl}}"` here. 

## Attribute Binding

**courses.component.ts**

```
colSpan = 2;
```

**courses.component.html**

```
  <table>
    <tr>
      <td [colspan]="colSpan">

      </td>
    </tr>
  </table>
```

`<td [colspan]="colSpan">`
> Error occurs in the template of component CoursesComponent.

Update bit more

```
  <table>
    <tr>
      <td [attr.colspan]="colSpan">

      </td>
    </tr>
  </table>
```

## Class Binding

We want that additional class sometimes based on different condition. 

We start the property binding syntax. Add the **class** property here and add **target class** here 

For example: 

**courses.component.ts**

```
isActive = true;
```

**courses.component.html**

```
<button class="btn btn-primary" [class.active]="isActive">Button</button>
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3ipi62j4vchv543a2rr7.PNG)

## Style Binding

Style binding is very similarity to class binding. 

For example: 

**courses.component.ts**

```
isActive = true;
```

**courses.component.html**

```
<button [style.backgroundColor]="isActive ? 'blue': 'white'">Style Binding</button>
```

**Output**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ec6tkk8wcet54zcpjyj6.PNG)


## Event Binding

Here add name of the event. Like **click**. Then we bind this to a **method** . 

**courses.component.html**

```
<button class="btn btn-primary" (click)="onSave()">Button</button>
```
So here is the button. Clicked. No look at the console. 

**courses.component.js**

```
onSave(){
    console.log('Button was clicked!')
  }
```

Okey here is the message. 

**Output** 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/wfw0vq9ws4vlcthlk4rj.PNG)

Sometimes we need get access **event object** that was raised event handler. 

For example mouse movement tell us x axis and y axis position. If you want to get access event object. We need add that parameter here. 

**courses.component.html**

```
<button class="btn btn-primary" (click)="onSave($event)">Button</button>
```

**courses.component.js**

```
onSave($event){
    console.log('Button was clicked!', $event)
  }
```

Then we calling this method `onSave()` pass the `$event`. Is `$` event angular known this. 

**Output** 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/t0n0j20zjljwy7ezdrhy.PNG)

All this properties here. 

## Event Bubbling

**courses.component.html**

```
 <div (click)="onDivClicked()">
  <button class="btn btn-primary" (click)="onSave($event)">Button</button>
 </div>
```

**courses.component.js**

```
onSave($event){
    console.log('Button was clicked!', $event)
  }
  onDivClicked(){
    console.log('Button was clicked!')
  }
```
Now let's see what happen. So when we click this button. We get two message at console. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/c8o46ubv7uh26jzfptw6.PNG)

The first one is the handler event of the button. And the second the handler of the **Div**. This is called event bubbling. How we can stop this. 

Bit more update. 

```
  onSave($event){
    $event.stopPropagation();
    console.log('Button was clicked!', $event)
  }
```

## Event Filtering

Here we have an input.

**courses.component.html**
```
<input type="text" (keyup)="onKeyUp($event)">
```
Pass the `$event` object here. And let's create this method our component.

**courses.component.js**
```
  onKeyUp($event){
    if($event.keyCode === 13){
        console.log('Enter was pressed.')
    }
  }
```
Let's perform an action. When user press enter into input field.
 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hbpjvvkaliic1nttxdj7.PNG)

Now **Angular** we have a better way to implement this exact feature.

So we can apply a **filter** when handling an event. 

**courses.component.html**
```
<input type="text" (keyup.enter)="onKeyUp()">
```

**courses.component.js**
```
   onKeyUp(){
        console.log('Enter was pressed.')
  }
```

**Output**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/9zsdvn8npnhxj7zi7web.PNG)

## Template Variables

Let's imagine we get the value was typed into the input field. How can we do it. There are two ways. One way to use the **event object**. So pass the event object here.    

**courses.component.html**
```
<input type="text" (keyup.enter)="onKeyUp($event)">
```
Add this parameter to our method. 

**courses.component.js**
```
    onKeyUp($event){
        console.log('Input value data: ', $event.target.value)
  }
```
Now `$event` and this is the standard event object into the DOM. So it has a **target** property. That references is this **value**. 

Now I typed **Bipon Biswas** and **Press Enter**. Now console we have **Bipon Biswas**

**Output**

   ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/da6ao6i3aapito3b9n7r.PNG)

> Now angular we have another way to solve this same problem. 

**courses.component.html**
```
 <input #email type="text" (keyup.enter)="onKeyUp(email.value)">
```
So here we have variable like this `#email`. Declare a variable using `#` tag. This is the name of our variable. This called this **template variable**. This references input field. 

Now instead of `$event` event object we can pass **email.value**

**courses.component.js**
```
     onKeyUp(email){
    console.log('Email: ', email)
 }
```
**Output**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/o1pbftshd802hll5dkz5.PNG)

So in a lot of cases we can use template variables to simply your code. 

## Two-way binding

Two-way binding gives components in your application a way to share data. Use two-way binding to listen for events and update values simultaneously between parent and child components.

Angular's two-way binding syntax is a combination of square brackets and parentheses, [()] . The [()] syntax combines the brackets of property **binding**, []

Bind the value property of this input object the DOM

**courses.component.html**
```
 <input [value]="email" type="text" (keyup.enter)="onKeyUp()">
```

We bind the value property of this input object in the DOM that is email field. If I initialize this `tomjerry@gmail.com`

**courses.component.js**

```
email = "tomjerry@gmail.com"

  onKeyUp(){
    console.log('Email: ', this.email)
  }
```
When we load this page input field should be populated with this email address. 

How we change this email input field data and press enter. Then no change in console. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hbabcqkcvg1mdq8qtfv1.PNG)

One way to implement this. This is one direction **component** to **view**. 

Bit attention. 

**courses.component.html**
```
<input [value]="email" type="text" (keyup.enter)="email = $event.target.value; onKeyUp()">
``` 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0bhuy7renfwt20xrfrpq.PNG)

With this implementation we have two-way binding. But as we can imagine is there a better way. Of course have. In angular have a special syntax.  

```
 <input [(ngModel)]="email" type="text" (keyup.enter)="onKeyUp()">
```
Instead of property binding we use two-way binding syntax. We use square brackets and parentheses, [()]. Instead of value we use **ngModel**. Angular have another **ngModle** built in directive called ngModel that is use implementing two-way binding. 

> Can't bind to 'ngModel' since it isn't a known property of 'input'.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mrv4iqsair7bfn97z9st.PNG)

We got this error. That's a familiar error. Basically are input object doesn't have a property call **ngModel**. But why we are getting this error. This **ngModel** directive is defined into **form**. In by default this is not imported into your application. So we want to use this **ngModel** and build any kind of form then need to import. How do we do that. 

So let's go to app module. Now look at this **@NgModule** decorator.  

**app.module.ts**

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

  imports: [
    BrowserModule,
    FormsModule
  ]
```
**Output**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/nueagz3bg36ap08v6y4d.PNG)

## Pipes

Another building block in pipe. Pipes to format data. Few sample Built-in pipe - Uppercase, Lowercase, Decimal, Currency, Percent. 

So let's see built-in pipes in action

**courses.components.ts**

```
  course = {
    title: "The Angular Course",
    rating: 4.9723,
    students: 30455,
    price: 160.45,
    releaseDate: new Date(2016, 3, 1)
  }
```
Course object in this properties. In the template simply rendering properties in the view. 

**courses.components.html** 

```
 {{course.title}}<br>
 {{course.students}}<br>
 {{course.rating | number}}<br>
 {{course.price}}<br>
 {{course.releaseDate}}
```
**Normal View**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/bbymvfjmu9u0vbg5uqzp.PNG)

How to pipe this. 

```
 {{course.title | uppercase}}<br>
 {{course.students | number}}<br>
 {{course.rating | number: '1.2-2'}}<br>
 {{course.price | currency: 'AUD': true:'3.2-2'}}<br>
 {{course.releaseDate | date:'shortDate'}}
```

Now let's look at the result.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/g8c0iwo7sfsndi6esy3l.PNG)

Rating has 4 digit after the decimal point. Wanna display 2 digit after the decimal point. I would add `2-2` . So **2** as the minimum and 2 maximum digit after the decimal point.  

Currency showing by default US dollar. Once again supply an argument. `{{course.price | currency: 'BDT'}}`. Also using multiple arguments. So here I can supply another argument. `{{course.price | currency: 'AUD': true}}`.  `true` to display  currency symbol. Finally optionally I can supply third argument. Once again `{{course.price | currency: 'AUD': true:'3.2-2'}}`. Similiar to decimal pipe. So here 3 minimum integer digit with 2 digit after decimal point. 


Thanks for reading. Happy journey.

[Angular Learning Day 1: Component](https://dev.to/bipon68/angular-learning-day-1-component-479m)
[Angular Learning Day 2: Angular Fundamentals](https://dev.to/bipon68/angular-learning-day-2-angular-fundamentals-3ci1)

[Source](https://github.com/bipon68/angular-practice)