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 mouseover event occurs when a mouse pointer comes over an element, and mouseout – when it leaves. These events are special, because they have property relatedTarget . This property complements target . When a mouse leaves one element for another, one of them becomes target , and the other one – relatedTarget .
Definition and Usage The ng-mouseover directive tells AngularJS what to do when a mouse cursor moves over the specific HTML element. The ng-mouseover directive from AngularJS will not override the element's original onmouseover event, both will be executed.
This means that mouseleave is fired when the pointer has exited the element and all of its descendants, whereas mouseout is fired when the pointer leaves the element or leaves one of the element's descendants (even if the pointer is still within the element).
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
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