Tips for sending data to CSS in Angular

I have an Angular application where I need to calculate the width of an element and store it in a variable called finalposition. Then, I want to move this element to the left by (finalposition)px when hovering over it. How can I achieve this styling effect only on hover?

component.ts


 ngAfterViewChecked(): void {
    this.finalposition = document.getElementById('spandiv').offsetWidth;
  }

component.html


  <input id="inputCustome" type="text">
  <p id="spandiv">xyzkskssss</p> 

component.css

#inputCustomer {
  text-align: center;
  position: relative;
  bottom: 7px;
  left: 2px;
}


#spandiv {
  position: absolute;
  right:145px;
  top: 40px;
  background-color: #6B6664;
  padding: 5px;
  color:white;
  font-weight: normal;
  display: block;
  opacity:0;
  overflow: hidden;

}


 #inputCustomer:hover + #spandiv {
  position: absolute;
  left: var(--finalPosition*2)+ "px"; // this value is not getting picked up
  top:40px;
  display: inline;
  opacity:1;

}  

Answer №1

You have the option to utilize (mouseenter) and (mouseleave) events in order to manipulate the value of finalPosition.

Give it a shot:

<input id="inputCustome" type="text" (mouseenter)="finalPosition = finalPosition * 2" (mouseleave) ="finalPosition = finalPosition / 2">
<p id="spandiv" [style.left]="finalPosition + 'px'" >xyzkskssss</p>

or

<input id="inputCustome" type="text" (mouseenter)="finalPosition = finalPosition * 2" (mouseleave) ="finalPosition = finalPosition / 2">
<p id="spandiv" [ngStyle]="{'left': finalPosition + 'px'}" >xyzkskssss</p>

Check out the Demo

Answer №2

If you want to add some interactive features using Angular, one way is to utilize Angular directives. You can take advantage of Angular events such as mouseover and mouseenter. For instance:

<input id="inputCustom" type="text" (mouseover)="onMouseOver()">

Alternatively, you can implement a directive like so:

<div styleHover >Hover over me</div>


@Directive({
  selector: '[styleHover]'
})
export class StyleOnHover {

  constructor(private el: ElementRef) {}

  @HostListener('mouseover') onHover(e) {
    console.log(e)
    console.log(this.el);
    // this.el.style => change the property
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Standard" approach for a Date instance

During my time in the Node REPL environment, the following output was displayed: > console.log(new Date()) 2023-08-15T09:21:45.762Z undefined > console.log(new Date().toString()) Sun Aug 15 2023 09:21:50 GMT+0000 (Coordinated Universal Time) undefine ...

Toggle JavaScript Query Display

Welcome to my HTML test website where I am testing show/hide JavaScript functionality. Upon loading the page, you may notice that everything is hidden until a button is clicked. <html> <head><title>Test</title> <scr ...

A data type that exclusively accepts values from an enumerated list without mandating the inclusion of every possible value within the enum

Here's a code snippet I'm working with: enum Foo { a, b, c } type Bar = { [key in keyof typeof Foo]: string; } const test: Bar = { a: 'a', b: 'b' }; I'm encountering an issue where the code is complaining ...

The div element fails to display even after invoking a JavaScript function to make it visible

As a newcomer to JavaScript & jQuery, please bear with me as I ask a very basic question: I have created the following div that I want to display when a specific JavaScript function is called: <div id='faix' class="bg4 w460 h430 tac poa ...

Javascript/Webpack/React: encountering issues with refs in a particular library

I've encountered a peculiar issue that I've narrowed down to the simplest possible scenario. To provide concrete evidence, I have put together a reproducible repository which you can access here: https://github.com/bmeg/webpack-react-test Here&a ...

I encountered difficulties connecting mongoose to my local MongoDB server

Hello Everyone! Currently, I am in the process of linking my node.js project to mongodb. Initially, everything worked smoothly when I used mongodb atlas. However, when I attempted to connect it using mongodb compass, I faced some issues and nothing seemed ...

When using ngx-slider in Angular, it unexpectedly fires off when scrolling on mobile devices

I am currently developing a survey application that utilizes ngx-sliders. However, I have encountered an issue on mobile devices where users unintentionally trigger the slider while scrolling through rows of slider questions, resulting in unintended change ...

What steps should I take to resolve this issue? ERROR TypeError: Unable to access property 'user' of null object

Is there a way to resolve the error I'm encountering in my project? The error message is: ERROR TypeError: null is not an object (evaluating 'userdata.user'). Using React Native Expo, I am facing this issue after logging into my app and navi ...

Tips for adjusting the vertical position of an image within a bootstrap column by a small amount

Apologies in advance if this question has already been addressed, and I am struggling to adapt it to my specific scenario. My objective is to adjust the positioning of the two images shown in the screenshot example below so that they align with the grey b ...

The enigma of TypeScript

Whenever I try to declare or initialize data members in a class, the following methods never seem to work: var view: string[]; var view: string[] = []; let view: string[]; let view: string[] = []; Even though the TypeScript documentation states that it s ...

Unable to reach the exposed port of the container

I am having difficulty accessing an Angular application that I have deployed within a container. Despite exposing the port in my Dockerfile and mapping the port in the docker-compose file, I still cannot access it from my web browser (Mozilla). There are ...

Tips for dynamically resizing the content area using CSS without the need for javascript

What I need is as follows: The blue area should resize when the browser window resizes. The header must be visible at all times. The blue area should start right after the header ends, not overlapping or appearing above it. The blue area should end befor ...

Universal customization for Material-UI Select

I am attempting to customize the appearance of a select component within a React project using MUI 5. Specifically, I want to modify the border size and color when the select component is in focus. While other components can be styled globally using styleO ...

My Ajax request in Javascript is encountering failure in Chrome due to AdBlock. What alternatives can I consider in this situation

Attempting to execute an ajax function $.ajax({ url: etsyURL, dataType: 'jsonp', success: function(data) { However, when running it on Chrome in a live environment, it fails due to adblock. I rely on javascript/jquery as my primary tools. Any ...

Comparing prevProps and this.props in React Native Redux: What is the most effective method?

Does anyone know how to efficiently handle triggering a function in my React Native app only when a specific prop has changed? This is the current implementation I have: componentDidUpdate(prevProps) { if (prevProps.a !== this.props.a) { <trigger ...

Error in browser caused by JQuery JavaScript, not Dreamweaver

I need help creating a webpage that can extract and display recent earthquake data based on user input location on Google Maps. I have been using Dreamweaver to test my code, and everything functions perfectly when I use the live webpage feature within th ...

The npm outdated -g command is producing an error message that states "Unable to read the length property of undefined"

I am currently facing an issue while trying to check the version status of my npm installed global packages. When I run the command npm outdated -g --depth=0 in the terminal, I encounter the following error: npm ERR! Cannot read property 'length&apos ...

Is there a way in JavaScript to convert a web page into a string?

I'm looking for a way to retrieve the HTML content of a webpage using JavaScript, even if it's on a different domain. Similar to what wget does but in JavaScript. I intend to use this for web crawling purposes. Could anyone guide me on how to fe ...

Stop the continuous AJAX loop or look for an alternative method to retrieve and compare a list of HTML pages

I am in need of a solution to insert a small script onto all of my website pages. The script must include the correct token for each of the 21 different domains I have. However, not all the sites are directly under the 'domain name' but are consi ...

Obtain the current name of the Material UI breakpoint

Looking for a MUI function called MaterialUIGiveMeCurrentBreakPointName that can help me execute an action in a component like so: const currentBreakPointName = MaterialUIGiveMeCurrentBreakPointName() if(currentBreakPointName === 'myCustomBreakPointN ...