DEV Community

Bipon Biswas
Bipon Biswas

Posted on

Angular Learning Day 3: Displaying Data and Handling Events

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"
Enter fullscreen mode Exit fullscreen mode

courses.component.html

<img src="{{imageUrl}}" alt="">
Enter fullscreen mode Exit fullscreen mode

or

<img [src]="imageUrl" alt="">
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

courses.component.html

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

      </td>
    </tr>
  </table>
Enter fullscreen mode Exit fullscreen mode

<td [colspan]="colSpan">

Error occurs in the template of component CoursesComponent.

Update bit more

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

      </td>
    </tr>
  </table>
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

courses.component.html

<button class="btn btn-primary" [class.active]="isActive">Button</button>
Enter fullscreen mode Exit fullscreen mode

Alt Text

Style Binding

Style binding is very similarity to class binding.

For example:

courses.component.ts

isActive = true;
Enter fullscreen mode Exit fullscreen mode

courses.component.html

<button [style.backgroundColor]="isActive ? 'blue': 'white'">Style Binding</button>
Enter fullscreen mode Exit fullscreen mode

Output
Alt Text

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>
Enter fullscreen mode Exit fullscreen mode

So here is the button. Clicked. No look at the console.

courses.component.js

onSave(){
    console.log('Button was clicked!')
  }
Enter fullscreen mode Exit fullscreen mode

Okey here is the message.

Output

Alt Text

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>
Enter fullscreen mode Exit fullscreen mode

courses.component.js

onSave($event){
    console.log('Button was clicked!', $event)
  }
Enter fullscreen mode Exit fullscreen mode

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

Output

Alt Text

All this properties here.

Event Bubbling

courses.component.html

 <div (click)="onDivClicked()">
  <button class="btn btn-primary" (click)="onSave($event)">Button</button>
 </div>
Enter fullscreen mode Exit fullscreen mode

courses.component.js

onSave($event){
    console.log('Button was clicked!', $event)
  }
  onDivClicked(){
    console.log('Button was clicked!')
  }
Enter fullscreen mode Exit fullscreen mode

Now let's see what happen. So when we click this button. We get two message at console.

Alt Text

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)
  }
Enter fullscreen mode Exit fullscreen mode

Event Filtering

Here we have an input.

courses.component.html

<input type="text" (keyup)="onKeyUp($event)">
Enter fullscreen mode Exit fullscreen mode

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.')
    }
  }
Enter fullscreen mode Exit fullscreen mode

Let's perform an action. When user press enter into input field.

Alt Text

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()">
Enter fullscreen mode Exit fullscreen mode

courses.component.js

   onKeyUp(){
        console.log('Enter was pressed.')
  }
Enter fullscreen mode Exit fullscreen mode

Output

Alt Text

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)">
Enter fullscreen mode Exit fullscreen mode

Add this parameter to our method.

courses.component.js

    onKeyUp($event){
        console.log('Input value data: ', $event.target.value)
  }
Enter fullscreen mode Exit fullscreen mode

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

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

courses.component.html

 <input #email type="text" (keyup.enter)="onKeyUp(email.value)">
Enter fullscreen mode Exit fullscreen mode

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)
 }
Enter fullscreen mode Exit fullscreen mode

Output

Alt Text

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()">
Enter fullscreen mode Exit fullscreen mode

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)
  }
Enter fullscreen mode Exit fullscreen mode

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

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()">
Enter fullscreen mode Exit fullscreen mode

Alt Text

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()">
Enter fullscreen mode Exit fullscreen mode

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

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
  ]
Enter fullscreen mode Exit fullscreen mode

Output

Alt Text

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)
  }
Enter fullscreen mode Exit fullscreen mode

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}}
Enter fullscreen mode Exit fullscreen mode

Normal View
Alt Text

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'}}
Enter fullscreen mode Exit fullscreen mode

Now let's look at the result.
Alt Text

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
Angular Learning Day 2: Angular Fundamentals

Source

Top comments (0)