我正在使用Angular 4,我在我的html模板上有这个div:
<div [class.myCssClass]="mouseOvered" (mouseout)="mouseOvered=false" (mouseover)="mouseOvered=true">Hover me</div>
这很好但我想从.ts组件文件中做同样的事情。
如何从.ts组件文件中执行此操作?
答案 0 :(得分:1)
据我所知,最好的方法是使用HostListener。
对于可以使用鼠标事件自行侦听的组件:
@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;
}
}
答案 1 :(得分:1)
使用[ngClass]
。
<div [ngClass]="{ overedClass: mouseOvered === true }"
(mouseout)="onMouseOut()"
(mouseover)="onMouseOver()">Hover me</div>
...并在你的.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;
}