首页 文章

Angular2 - 使用NgFor元素进行HostListener /绑定

提问于
浏览
1

我有用户列表 . 我希望当光标悬停在按钮上时,它将 *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主题 .

Hostbinding ngIf in Angular2

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 回答

  • 0

    你忘记的是将变量绑定到元素

    <div onUserHover [ngIf]="ngif" *ngIf="ngIf">
    

    你的指令不起作用?您是否记得将该指令添加到@NgModule的声明属性中?很容易忘记!在浏览器工具中打开控制台并查找如下错误:EXCEPTION:模板解析错误:无法绑定到'myHighlight',因为它不是'p'的已知属性 . Angular检测到您正在尝试绑定某些内容,但它无法在模块的声明数组中找到此指令 . 在声明数组中指定HighlightDirective后,Angular知道它可以将指令应用于此模块中声明的组件 .

相关问题