I have list of users. I want that when the cursor hover on the button, it sets *ngIf
to true and then displays information about the user (and false when the cursor leave the button).
user-list.html
:
<div *ngFor="let user of users">
<h1>{{user.name}}</h1>
<div onUserHover *ngIf="ngIf">
<p>{{user.description}}</p>
</div>
</div>
user-list.component.ts
:
import { Component, OnInit } from '@angular/core';
import { User } from 'class/user';
import { UserService } from 'user/user.service';
@Component({
selector: 'user-list',
templateUrl: 'user-list.component.html',
providers: [UserService]
})
export class UserListComponent implements OnInit {
users: User[];
constructor(private userService: UserService) {
};
ngOnInit(): void {
this.getUsers();
}
getUsers(): void {
this.userService.getUsers().then(users => this.users = users);
}
toggleUser(user: User): void {
user.active = !user.active;
}
}
I used "toggleUser(user: User)" like this :
(click)='toggleUser(user)'
, however I want now a onHover
instead of click.
I saw the tutorial about directives attributes on Angular.io website and a StackOverflow topic on HostBinding('ngIf')
.
onUserHover.directive.ts
:
import { Directive, ElementRef, HostBinding, HostListener } from '@angular/core';
@Directive({ selector: '[onUserHover]' })
export class OnUserHoverDirective {
constructor(private el: ElementRef) {
}
@HostBinding('ngIf') ngIf: boolean;
@HostListener('mouseenter') onMouseEnter() {
console.log('onMouseEnter');
this.ngIf = true;
}
@HostListener('mouseleave') onmouseleave() {
this.ngIf = false;
}
}
But I have one error on the browser :
Can't bind to `ngIf` since it isn't a known property of `div`
What can I do to implement this feature in Angular 2 style ?