我有用户列表 . 我希望当光标悬停在按钮上时,它将 *ngIf
设置为true,然后显示有关用户的信息(当光标离开按钮时为false) .
用户list.html
<div *ngFor="let user of users">
<h1>{{user.name}}</h1>
<div onUserHover *ngIf="ngIf">
<p>{{user.description}}</p>
</div>
</div>
用户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而不是click .
我在Angular.io网站上看到了关于指令属性的教程,在HostBinding('ngIf')上看到了一个stackOverflow主题 .
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`
如何以Angular2风格实现此功能?
1 回答
你忘记的是将变量绑定到元素