I am using Angular 4 and I have this div on my html template:
<div [class.myCssClass]="mouseOvered" (mouseout)="mouseOvered=false" (mouseover)="mouseOvered=true">Hover me</div>
This works great but I would like to do this same thing from the .ts component file instead.
How can I do this from the .ts component file?
According to me, The best way would be to use a HostListener.
For a component to listen on itself on the mouse events you can use:
@Component({
selector: 'my-component'
template: '<div [class.myCssClass]="mouseover"'
})
class MyComponent {
mouseover:boolean;
@HostListener('mouseover')
onMouseOver() {
this.mouseover = true;
}
@HostListener('mouseout')
onMouseOut() {
this.mouseover = false;
}
}
Use [ngClass]
.
<div [ngClass]="{ overedClass: mouseOvered === true }"
(mouseout)="onMouseOut()"
(mouseover)="onMouseOver()">Hover me</div>
... and in your .ts:
// contains name of any class that you want to apply
private overedClass: string = 'myCssClass';
private mouseOvered: boolean;
onMouseOver() {
this.mouseOvered = true;
}
onMouseOut() {
this.mouseOvered = false;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.