我有用户列表。我希望当光标悬停在按钮上时,它设置*ngIf
为 true,然后显示有关用户的信息(当光标离开按钮时为 false)。
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;
}
}
我像这样使用“toggleUser(user:User)”:
(click)='toggleUser(user)'
但是我现在想要一个onHover
而不是点击。
我在 Angular.io 网站上看到了关于指令属性的教程,在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;
}
}
但我在浏览器上有一个错误:
Can't bind to `ngIf` since it isn't a known property of `div`
我该怎么做才能以 Angular 2 风格实现此功能?