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

Tips for successfully using `cols=""` within a grid container alongside a textarea

It seems that both Chrome and Firefox are not following the cols attribute on textarea elements within a grid container: .grid { display: grid; } textarea:not([cols]) { width: 100%; } <h2>Not in a grid container:</h2> <div> <tex ...

React js web application facing excessive content problem

I am encountering an overflow issue with the styles sheet I'm using on mobile and tablet views, but it works fine on desktop view. Can anyone provide a solution to this problem? I am developing a ReactJS web app hosted on Firebase. When I include fewe ...

After entering text manually, the textarea.append() function ceases to function properly

I've encountered a puzzling issue with a tiny fiddle I created: https://jsfiddle.net/wn7aLf3o/4/ The scenario is that clicking on 'append' should add an "X" to the textarea. It functions perfectly until I manually input some text in the te ...

Tips on continuously making calls to a backend API until receiving a successful response with status code 200

While working on my Angular project, I have encountered a situation where I need to make calls to a backend API. If the response is not 200 OK, I have to keep calling the API every 30 seconds until I receive a successful response. In Angular, I usually ca ...

What is the best way to elucidate this concept within the realm of TypeScript?

While diving into my ts learning journey, I came across this interesting code snippet: export const Field:<T> (x:T) => T; I'm having trouble wrapping my head around it. It resembles the function definition below: type myFunction<T> = ...

Utilize interpolation with ES6 and an Angular 1.4 directive

Currently experimenting with the unique ES6 + Angular combination and facing a challenge in interpolating an html string within a directive that includes scope bindings. We have attempted the following approach: Current scenario The code below is functi ...

I'm only seeing output on two of my input boxes - what's going on?

Currently in the process of learning JQUERY/HTML, I decided to create a shopping cart. My goal is to display the subtotal, tax, shipping costs, and total cost in input boxes. While I successfully displayed the sub total and shipping cost, I encountered an ...

Ways to format the initial letter of a word as BOLD

Looking to make the first letter of certain words bold on a button in my UI that says, "Active Engagement" and "Active Non-Engagement". How can this be achieved? For example: Active Engagement, Active Non-Engagement The code for the buttons is as follows ...

The mat-table fails to populate with data retrieved from the rest service

I have successfully fetched an array from my REST service and displayed some information from the response on the page. However, I am facing issues populating my mat-table and I'm unsure of the cause. The mat-table was functioning properly in the past ...

Enhancing Styled Components in Material-UI with custom props and themes using Typescript

I am exploring the use of the Material UI styled components API to incorporate both a custom theme and some props into a specific custom element. Although I have managed to get either a custom theme or props working individually, I am struggling to make t ...

Why isn't my Vue2 data updating in the HTML?

Starting my journey with Vue, I have been finding my way through the documentation and seeking support from the Vue community on Stack Overflow. Slowly but steadily, I am gaining a better understanding of how to create more complex components. The issue I ...

The function fails to return a true value

Why is true never returned even when the given name exists in the array rows and the if(rows[i].userName == name) condition is met? function checkIfUserExists(name){ var isUserExists = false; OOTW.MYSQL.query('SELECT * FROM Time',functio ...

Searching for values within an array using the ".includes" method

I'm curious if there's a method to determine if a string contains any characters that are also present in an array? const array = ["cake", "hello", "ok"]; const string = "hello"; let result = string.include ...

Include an additional Div tag in the existing row

I've been attempting to include an additional div, but it consistently appears as the second row.. I want all of them to be on the same row and aligned with each other. Here is the HTML code: <div class="content-grids"> <div clas ...

What are the steps to implement cp-react-tree-table in my application?

Recently diving into TypeScript, I decided to explore the demo provided by https://www.npmjs.com/package/cp-react-tree-table in order to incorporate this control into my project. However, I encountered some unexpected information. After conducting a thoro ...

Design a progress bar that advances in increments of at least two and up to a maximum of

My task involves managing a simple list. const [progressBar, setProgressBar] = useState([ { isActive: false, name: "step1" }, { isActive: false, name: "step2" }, { isActive: false, name: "step3" }, { isActive ...

Displaying Edit and Delete options upon hovering over the data row

I'm working on a table that uses ng-repeat on the <tr> element. In the last column of each row, I have edit/delete links that should only be visible when the user hovers over the <tr> element. <tr ng-repeat="form in allData | filter:se ...

When attempting to pass Rgraph image data through a jQuery AJAX call, a 403 Forbidden error is being

I have been working on a project that involves creating graphs/charts using the Rgraph PHP library. To generate these charts, my script follows these steps: Calculate the graph points and render the graph using the Rgraph Draw() method. Create an image d ...

Guide to navigating to a specific module within an Angular 2 application directly from the index page

As a newcomer to angular2, I recently obtained a sample login and registration code online. However, when I run the code, it displays the index page instead of the "login" module located within the app folder. Can someone please advise me on how to redire ...

Is there a way to incorporate multiple rules from data into a text component using Vuetify?

I'm looking to establish specific rules within a mixin for my components. Allow me to provide a straightforward example of my request: Example Link The code snippet: <v-text-field :rules="[nbRules, requiredRules]" outlined v-model="name" label ...