Tuesday, November 22, 2016

Angular 2 Part 4.2 - Event Binding

In Part 4.1, I covered Property Binding and Class Binding. Both is JavaScript to HTML data flow.

In Part 4.2, I am going to introduce Event Binding which is HTML to JavaScript data flow. Any standard DOM Event can be listened for by wrapping it in parentheses and removing the "on" at the beginning of the word. Example:
  • <div (mouseover)="call()">
  • <input (blur)="call()">
  • <input (focus)="call()">
  • <input type="text" (keydown)="call()">
  • <form (submit)="call()">
Sometime, you need additional event data like which key is pressed or where the mouse is on the screen. We can pass it in to our component method with $event. Example:
<input type="text" (keydown)="showKey($event)">

showKey(event){
  //Prompt on key is pressed
  alert(event.keycode); 
}
<h2 (mouseover)="getCoord($event)">Hover Me</h2>

getCoord(event){
  // Display mouse X and Y coordinate.
  consolo.log(event.clientx + ", " + event.clienty);
}
I am going to add plus and minus button and bind this 2 buttons into a method in our car part example.

We add quantity property into our model.
export class CarPart {
  ...
  quantity:number;
}
Add quantity data into mock.ts.
export const CARPARTS : CarPart[] = [{ 
  "id":1,
  ...
  "quantity":0
},
{
  "id":2,
  ...
  "quantity":0
},
{
  "id":3,
  ...
  "quantity":0
}] // Example of object
Add 2 methods into car-parts.component.ts.
export class CarPartComponent {
  carParts : CarPart[];
  ngOnInit() {
    this.carParts = CARPARTS;
  }

  totalCarParts(){
    let sum = 0;
    for (let carPart of this.carParts) {      sum += carPart.inStock;
    }
    return sum;
  }

  upQuality(carPart){
    if (carPart.quantity < carPart.inStock) carPart.quantity++;
  }

  downQuality(carPart){
    if (carPart.quantity != 0) carPart.quantity--;
  }
}
Add 2 buttons into car-parts.component.html and bind to our created methods on click event.
<li *ngFor="let carPart of carParts" [class.featured]="carPart.featured">
  <h2>{{carPart.name | uppercase}}</h2>
    <img [src]="carPart.image">
    <p class="description">{{carPart.description}}</p>
    <p class="price">{{carPart.price | currency:"EUR":true}}</p>
    <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>
    <p *ngIf="carPart.inStock === 0">Out of stock</p>
    <p><button (click)="downQuality(carPart)">-</button> {{carPart.quantity}} <button (click)="upQuality(carPart)">+</button></p>
</li>
Here is out put:




















Download Car Part Source:
https://github.com/htsiah/angular2-carparts

No comments:

Post a Comment