how do I change css class property transform on mouse move event in angular like java script

Viewed 377

like this example

html code

const container = document.querySelector(".container");
const card = document.querySelector(".card");
container.addEventListener("mousemove", (e) => {
  let xAxis = (window.innerWidth / 2 - e.pageX) / 25;
  let yAxis = (window.innerHeight / 2 - e.pageY) / 25;
  card.style.transform = `rotateY(${xAxis}deg) rotateX(${yAxis}deg)`;
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: "Poppins", sans-serif;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  perspective: 1000px;
}

.container {
  width: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card {
  transform-style: preserve-3d;
  min-height: 60vh;
  width: 500px;
  border-radius: 30px;
  padding: 0rem 5rem;
  box-shadow: 0 20px 20px rgba(0, 0, 0, 0.2), 0px 0px 50px rgba(0, 0, 0, 0.2);
}
<div class="container">
  <div class="card">
    <h1 style="margin: 40px 40px;">Sample Text
      <h1>
  </div>
</div>

2 Answers

You can do it this way: html

<div class="container" (mousemove)="onMousemove($event)">
  <div class="card" #card>
    <h1 style="margin: 40px 40px;">Sample Text<h1>
  </div>
 </div>

component ts:

import {
  Component,
  Renderer2,
  ElementRef,
  ViewChild,
} from "@angular/core";

export class YourComponent {
  @ViewChild("card", { static: false }) cardRef: ElementRef;

  constructor(private renderer: Renderer2) {}

  onMousemove(event) {
    let xAxis = (window.innerWidth / 2 - e.pageX) / 25;
    let yAxis = (window.innerHeight / 2 - e.pageY) / 25;
    this.renderer.setAttribute(this.cardRef, "style", `transform: rotateY(${xAxis}deg) rotateX(${yAxis}deg)`);
  }
}

Let me know if there is any problem. Good luck :)

There are lots of ways to do this in Angular but the preferred method is the @HostListener.

import { Component, HostListener } from '@angular/core';

@Component({
  ...
})
export class TestComponent {
  @HostListener('mousemove', ['$event']) 
  onMouseMove(e) {
    console.log(e);
  }

  ...
}
Related