Using vanilla js code in Angular 2 (angular-cli)

2019-08-03 02:14发布

问题:

I am trying to implement the Vanilla Tilt JS plugin in my project, but I can't even seem to find a way of using vanilla js imports in my project.

So far, I have tried using it as a directive, just like you would use a jQuery plugin by using ElementRef , Input etc. from @angular/core.

I have included the script in my .angular-cli.json file under scripts: directly from the npm package that I have installed for Vanilla Tilt JS.

And I was thinking about using it as a directive, since it has its own data-tilt attribute like so:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
    selector: '[data-tilt]'
})
export class ParallaxDirective {
    constructor(private el: ElementRef) {

    }
}

But I can't find a way to do this, despite my efforts so far. I am new to Angular 2.

My question is:

Is it possible to use a plain javasciprt plugin inside Angular 2 , and if possible , how can I implement the Vanilla-Tilt JS plugin?

回答1:

You should be able to import Vinilla-tilt and use the element reference passed into the constructor.

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

const VanillaTilt = require('vanilla-tilt');

@Directive({
    selector: '[data-tilt]'
})
export class ParallaxDirective {
    constructor(private el: ElementRef) {
      VanillaTilt.init(el.nativeElement, {
        max: 25,
        speed: 400
      });
    }
}