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;
}
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
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With