3

I am running angular app, I calculate width of element and store it under variable finalposition and I want to move to left (finalposition)px. I want this style property to be applied only on hovering over the element. How to do this?

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;

}  

2
  • Hi, How to apply ngStyle only on hovering Commented Dec 5, 2019 at 17:42
  • Have you tried the solution? Commented Dec 6, 2019 at 6:23

3 Answers 3

6

You can use (mouseenter) and (mouseleave) to set finalPosition value.

Try:

<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>

Demo

Sign up to request clarification or add additional context in comments.

Comments

1

You can leverage the power of Angular directive to do this kind of stuff. You can also use the Angular events such as mouseover, mouseenter. For eg.

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

or You can use the directive like

<div styleHover >Hover 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
  }
}

1 Comment

I like this approach a lot.
1

To pass controller variables to SCSS files follow this approach, using CSS variables within the SCSS file

TS

constructor(private ref: ElementRef) {}

ngOnInit() {
  this.initCssVars()
}

private initCssVars() {
  const el = this.ref.nativeElement
  el.style.setProperty('--circle-color', this.circleColor())
}

SCSS

.my-class {
  color: var(--circle-color);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.