How to use mouseover and mouseout in Angular 6
I have this older Angular code which works but not in the latest version of Angular 6.
<div ng-mouseover="changeText=true" ng-mouseleave="changeText=false" ng-init="changeText=false">
<span ng-hide="changeText">Hide</span>
<span ng-show="changeText">Show</span>
</div>
How do i make this work for Angular 6? I understand I have to use (mouseover)
and (mouseout)
but I couldn't implement it successfully.
The Angular6 equivalent code should be:
app.component.html
<div (mouseover)="changeText=true" (mouseout)="changeText=false">
<span *ngIf="!changeText">Hide</span>
<span *ngIf="changeText">Show</span>
</div>
app.component.ts
@Component({
selector: 'app-main',
templateUrl: './app.component.html'
})
export class AppComponent {
changeText: boolean;
constructor() {
this.changeText = false;
}
}
Notice that there is no such thing as $scope
anymore as it existed in AngularJS. Its been replaced with member variables from the component class. Also, there is no scope resolution algorithm based on prototypical inheritance either - it either resolves to a component class member, or it doesn't.
Adding to what was already said.
if you want to *ngFor
an element , and hide \ show elements in it, on hover, like you added in the comments, you should re-think the whole concept.
a more appropriate way to do it, does not involve angular at all.
I would go with pure CSS instead, using its native :hover
property.
something like:
App.Component.css
div span.only-show-on-hover {
visibility: hidden;
}
div:hover span.only-show-on-hover {
visibility: visible;
}
App.Component.html
<div *ngFor="let i of [1,2,3,4]" > hover me please.
<span class="only-show-on-hover">you only see me when hovering</span>
</div>
Demo: STACKBLITZ
To avoid blinking problem use following code
its not mouseover and mouseout instead of that use mouseenter and mouseleave
**app.component.html**
<div (mouseenter)="changeText=true" (mouseleave)="changeText=false">
<span *ngIf="!changeText">Hide</span>
<span *ngIf="changeText">Show</span>
</div>
**app.component.ts**
@Component({
selector: 'app-main',
templateUrl: './app.component.html'
})
export class AppComponent {
changeText: boolean;
constructor() {
this.changeText = false;
}
}