【发布时间】:2017-03-31 11:45:52
【问题描述】:
我有用户列表。我希望当光标悬停在按钮上时,它将*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(用户:用户)”:
(click)='toggleUser(user)',但是我现在想要 onHover 而不是点击。
我在 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`
如何以 Angular 2 风格实现此功能?
【问题讨论】:
-
你可以简单地用 css 做,那你为什么要让事情变得如此复杂?
-
@VivekDoshi 我也希望在代码中这样做,以防止 CSS 规则。更容易调试。
-
您可能对
this绑定有问题,指的是HTML 元素而不是您的类。尝试将函数绑定到您的类。 -
这根本没有意义。您无法从指令中访问父 ngIf,此外,您希望在鼠标悬停时附加内容并在鼠标离开时将其删除。你想如何悬停一个不存在的元素?
-
标签: angular angular-ng-if ngfor angular2-hostbinding