首页 > 解决方案 > 将 vanilla-tilt.js 添加到 Angular 6 组件(Angular 组件中的外部 js 库)

问题描述

您好,我想在我的一个角度组件中使用名为 vanilla-tilt.js 的第三方 js 库。这是图书馆的链接:

https://micku7zu.github.io/vanilla-tilt.js/

到目前为止我所做的是:使用 npm 安装并将其链接到我的 angular.json 文件中,如下所示:

"scripts": [
    "node_modules/vanilla-tilt/dist/vanilla-tilt.js"
]

然后在我的 component.ts 中我做了以下事情(我只提供了必要的代码并且'.about-pic'<img>我在我的 html 文件中选择的):

import { VanillaTilt } from 'vanilla-tilt/dist/vanilla-tilt.js';

export class AboutComponent implements OnInit, AfterViewInit {
  ngAfterViewInit() {
    VanillaTilt.init(document.querySelector('.about-pic'), {
      max: 25,
      speed: 400
    });
  }
}

ngAfterViewInit()从上面链接的网站中获取了代码,在“JS Way”下

我以为我正确导入了这个外部库,但我在控制台中收到以下错误:

ERROR TypeError: Cannot read property 'init' of undefined

我想我不太了解在 Angular 组件中安装第三方 js 库的概念。

任何人都可以帮忙吗?

谢谢!

标签: angular

解决方案


按照https://micku7zu.github.io/vanilla-tilt.js/ JS 方式,我在 ngOnInit 中尝试了同样的方法。它对我有用。

  1. npm install vanilla-tilt
  2. 在 ts 文件中声明 var VanillaTilt
  3. ngOnInit() {

    VanillaTilt.init(document.querySelector(".tilt-image"), { max: 25, speed: 400 });

    VanillaTilt.init(document.querySelectorAll(".tilt-image"));

    }

  4. 在 html
    div 类="倾斜倾斜图像" 数据倾斜数据倾斜眩光="true" 数据倾斜规模="1.1"
    img src="assets/images/sample.png"
    /div

注意:“倾斜图像”是你的元素


推荐阅读