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

∥☆過路亽.° 提交于 2019-12-11 06:53:54

问题


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
      });
    }
}


来源:https://stackoverflow.com/questions/42536186/using-vanilla-js-code-in-angular-2-angular-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!