Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add vanilla-tilt.js to Angular 6 component (external JS library in Angular component)

Tags:

angular

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 I've 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 (I'm 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. What can I try next?

like image 213
cup_of Avatar asked Mar 14 '26 16:03

cup_of


1 Answers

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

like image 80
Vignesh AG Avatar answered Mar 17 '26 11:03

Vignesh AG