HammerJS in Angular

Posted By :Mahima Gautam |31st May 2019

HammerJS is a mainstream library that encourages you to include support for touch gestures (for example swipe, dish, zoom, pivot) to your page.

 

Introduction

 

We will fabricate a carousel of an avatar. The client can swipe left or swipe ideal to see every avatar. 

 

App Setup

 

How about we investigate how our envelope structure resembles. We'll have an application organizer which contains our avatar carousel and main.ts file for bootstrapping our application.

 

|- app/
   |- app.component.html
   |- app.component.css
   |- app.component.ts
   |- app.module.ts
   |- main.ts
|- index.html
|- tsconfig.json

 

App Component

 

How about we begin with our application part. In this segment, we will characterize our list of avatars and handle the swipe occasion and show/conceal a symbol dependent on the swipe sequence.

 

// app/app.component.ts

import { Component } from '@angular/core';

@Component({
   moduleId: module.id,
   selector: 'my-app',
   templateUrl: 'app.component.html',
   styleUrls: ['app.component.css']
})
export class AppComponent {
   // constant for swipe action: left or right
   SWIPE_ACTION = { LEFT: 'swipeleft', RIGHT: 'swiperight' };

   // our list of avatars
   avatars = [
       {
           name: 'kristy',
           image: 'http://semantic-ui.com/images/avatar2/large/kristy.png',
           visible: true
       },
       {
           name: 'matthew',
           image: 'http://semantic-ui.com/images/avatar2/large/matthew.png',
           visible: false
       },
       {
           name: 'chris',
           image: 'http://semantic-ui.com/images/avatar/large/chris.jpg',
           visible: false
       },
       {
           name: 'jenny',
           image: 'http://semantic-ui.com/images/avatar/large/jenny.jpg',
           visible: false
       }
   ];

   // action triggered when user swipes
   swipe(currentIndex: number, action = this.SWIPE_ACTION.RIGHT) {
       // out of range
       if (currentIndex > this.avatars.length || currentIndex < 0) return;

       let nextIndex = 0;

       // swipe right, next avatar
       if (action === this.SWIPE_ACTION.RIGHT) {
           const isLast = currentIndex === this.avatars.length - 1;
           nextIndex = isLast ? 0 : currentIndex + 1;
       }

       // swipe left, previous avatar
       if (action === this.SWIPE_ACTION.LEFT) {
           const isFirst = currentIndex === 0;
           nextIndex = isFirst ? this.avatars.length - 1 : currentIndex - 1;
       }

       // toggle avatar visibility
       this.avatars.forEach((x, i) => x.visible = (i === nextIndex));
   }
}

 

  1. We will deal with swipe left and swipe right occasion utilizing a similar capacity swipe. 
  2. Swipe takes two parameters: the first parameter is the present record of the chose symbol, the second parameter
  3.  

  4.  is discretionary, the swiping activity either left or right. 
  5. You see that we pronounce a consistent SWIPE_DIRECTION and the esteem is swipe left or swipes right. 
  6. Allude to HammerJS documentation, HammerJS handles 5 swipe occasions: swipe, swipe left, swipe-right, swipe-up, swipe-down. For our situation, we simply handle swipe-left and swipe-right. 
  7. We will call this swipe activity later in our HTML see.


 

HTML View

 

<!-- app/app.component.html -->
<div>
   <h4>Swipe Avatars with HammerJS</h4>
   <!-- loop each avatar in our avatar list -->
   <div class="swipe-box"  
       *ngFor="let avatar of avatars; let idx=index"
       (swipeleft)="swipe(idx, $event.type)" (swiperight)="swipe(idx, $event.type)"
       [class.visible]="avatar.visible" [class.hidden]="!avatar.visible">
       <div>
           <img [src]="avatar.image" [alt]="avatar.name">
       </div>
       <div>
           <a class="header">{{avatar.name}}</a>
       </div>
   </div>
</div>

 

  1. We circle through every symbol utilizing *ngFor order, we announce a nearby factor IDX to hold the present record of the symbol. 

  2. At that point, we will deal with swipe-left and swipe right occasion, call the swipe work that we proclaimed before. 
  3.  

  4. $event is the occasion object. We needn't bother with the data of the entire $event object. We need just $event. type which returns a string of swipe-left or swipe-right. 
  5. [class.visible] or [class.hidden]. We will include or evacuate these two CSS classes dependent on the avatar.visible property.


 

Component Styling

 

We can utilize semantic-ui CSS to facilitate our styling, however that is not neccessary for our motivations. Aside from that, there are two or three custom CSS classes that we have to include for our part.

 

.swipe-box {
   display: block;
   width: 100%;
   float: left;
   margin: 0;
}

.visible {
   display: block;
}

.hidden {
   display: none;
}

  1. We need all our symbol cards stack over one another, along these lines, we use .swipe-box to skim every one of the symbols

  2. .obvious and .covered up are utilized to appear/conceal the symbol card.


 

HammerJS JavaScript

 

We're currently finished with our segment. How about we proceed onward to setting up HammerJS. In the first place, we have to incorporate the HammerJS Javascript document in our primary view index.html file.

 

<!-- index.html -->
<head>
...
   <!-- Hammer JS -->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.js"></script>
....
</head>

As a matter of course, the work area program doesn't bolster the touch occasion. HammerJS has an augmentation called contact emulator.js that gives a troubleshoot instrument to imitate contact support in the program. You can incorporate these lines in the index.html like this before the HammerJS document:

 

<!-- index.html -->
<head>
...
   <!-- Hammer JS Touch Emulator: Uncomment if for desktop -->
   <script src="http://cdn.rawgit.com/hammerjs/touchemulator/master/touch-emulator.js"></script>
   <script>
   TouchEmulator();
   </script>
...
</head>

Since I run this model in plunker, I simply incorporate the HammerJS CDN url. On the off chance that you need to deal with your bundle locally, you may run the accompanying order:

 

npm install hammerjs --save

 

At that point, incorporate the JS records in your fabricate.

 

On the off chance that we do exclude HammerJS record, a blunder message will be tossed: "Hammer.js isn't stacked, can not tie swipeleft occasion".


 

Application Module

 

Of course, on the off chance that you don't have any custom design, you can utilize HammerJS straight away. Angular2 bolsters HammerJs out of the case. No compelling reason to incorporate anything amid application bootstrap. Your application module will look something like this:

 

// app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }   from './app.component';

@NgModule({
 imports:      [ BrowserModule ],
 declarations: [ AppComponent ],
 bootstrap:    [ AppComponent ],
 providers:    [ ]
})

export class AppModule { }

Summary

 

Angular 2 make it extremely simple to incorporate with HammerJS for contact signal occasion identification. That is it. Happy coding!

 

About Author

Mahima Gautam

Mahima has a good knowledge of HTML and CSS. She is working as a UI Developer and she loves to dance in her free time.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us