Search code examples
svgtypescriptangularhammer.jsangular2-directives

Adding hammer.js actions to a svg rectangle in a component Angular2


I’m working on an Angular 2 app and I have a component which inclundes a simple SVG rectangle, I’m trying to use Hammer.js library to be able to deplace and reform this SVG rectangle inside the view of my component, therefore I’ve done those steps:

  1. I’ve downloaded and copied 3 files to my project repository
hammer.js 
hammer.min.js 
hammer.min.map
  1. I’ve added this script tag to my index head:
<script src="dev/jqueryLibs/hammer/hammer.js" type="text/javascript"></script>

And I get this error in the console:

Uncaught TypeError: Cannot read property 'addEventListener' of null

  1. I’ve tried to import it in my component and add reference betwen the methode and the svg element, like this:

TS.File contents:

import {Component, ElementRef, AfterViewInit } from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {FORM_DIRECTIVES} from "angular2/common";

@Component({
    selector: 'content',
    templateUrl: 'content.component.html',
    styleUrls: ['content.component.css'],
    directives: [FORM_DIRECTIVES],
})

export class ContentComponent implements AfterViewInit{

static hammerInitialized = false;
constructor(private el:ElementRef)
    {}
ngAfterViewInit() {
        console.log('in ngAfterViewInit');
        if (!ContentComponent.hammerInitialized) {
            console.log('hammer not initialised');

            var myElement = document.getElementById('test1');
            var hammertime = new Hammer(myElement);
            hammertime.on('swiperight', function(ev) {
                console.log('caught swipe right');
                console.log(ev);
            });

            ContentComponent.hammerInitialized = true;
        } else {
            console.log('hammer already initialised');
        }
    }

View file contents:

<svg class="simulation">
  <rect id="test1" x="20" y="500" height="150" width="200" style="stroke:#EC9A20;stroke-width: 15; fill: none"/>
</svg>

Therefore I still am not able to move my SVG rectangle and it seems that Hammer.js is not even running according to this console message:

hammer not initialised

Anybody can tell me where is the error or what should I do?


Solution

  • This was resolved: The script tag of hammer declaration must be placed after the jquery-ui library declaration in HTML file.

    <script src="./dev/resources/js/jquery.js"></script>
    <script src="./dev/resources/js/jquery-ui.js"></script>
    
    <script src="./dev/jqueryLibs/jquery-1.12.1.min.js"></script>
    <script src="./dev/jqueryLibs/jquery-migrate-1.2.1.min.js"></script>
    
    <!--importer ici la js de bootstrap-->
    <script src="node_modules/bootstrap/dist/js/bootstrap.js"></script>
    
    <!--Importer ici hammer.js-->
    <script src="dev/jqueryLibs/hammer/hammer.js" type="text/javascript"></script>