3

Hello I would like to use a third party js library called vanilla-tilt.js in one of my angular components. Here is the link to the library:

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

What Ive done so far is: Installed with npm and linked it into my angular.json file like so:

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

Then in my component.ts I did the following (im only supplying the necessary code and '.about-pic' is the <img> I am selecting in my html file):

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

I got the code in ngAfterViewInit() from the website I linked above, under "JS Way"

I thought I imported this external library correctly, but I am getting the following error in the console:

ERROR TypeError: Cannot read property 'init' of undefined

I guess am not quite understanding the concept of installing third party js libraries in angular components.

Can anyone help?

Thanks!

cup_of
  • 5,779
  • 6
  • 37
  • 81
  • 1
    Have a look at [this](https://stackoverflow.com/a/50824362/5695162) and [this](https://stackoverflow.com/a/50303509/5695162) – Vikas Jul 08 '18 at 07:23

1 Answers1

2

As per https://micku7zu.github.io/vanilla-tilt.js/ JS way, i tried the same in ngOnInit. It worked for me.

  1. npm install vanilla-tilt
  2. declare var VanillaTilt in ts file
  3. ngOnInit() {

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

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

    }

  4. In html
    div class="tilt tilt-image" data-tilt data-tilt-glare="true" data-tilt-scale="1.1"
    img src="assets/images/sample.png"
    /div

Note : "tilt-image" is your element

Vignesh AG
  • 31
  • 2
  • declare and init fixed it. FYI - In Angular when you move vanilla-tilt html from index/main page to component they don't work. The solution is to initialize the related elements as mentioned above. Thanks. – Dash Jul 25 '19 at 08:24
  • If you want to run this in Angular 9+, you need to import vanilla-tilt first so: import 'vanilla-tilt'; declare var VanillaTilt; will work – hatirlatici Feb 12 '21 at 19:50