Angular 5 属性指令不适用于鼠标事件

mut*_*ard 2 attributes directive angular angular5

我对属性指令有疑问。我已经按照教程进行操作了。

指令是使用 CLI 生成的,因此我使用了ng g directive <directivename>,并且特意与 一起放在顶层app.module.ts

我的app.module.ts看起来像这样(由于模块的专有名称,我必须省略所有导入):

// Directives
import { EventhoverDirective } from './eventhover.directive';

@NgModule({
  declarations: [
    // all the relevant component inputs are here
    EventhoverDirective
  ],
  imports: [
   // modules are here
  ],
  providers: [
    // providers are here
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

指令本身看起来像:

import { Directive, HostListener, OnInit, Renderer2, ElementRef } from '@angular/core';

@Directive({
  selector: '[appEventhover]'
})
export class EventhoverDirective implements OnInit {

  constructor(private el: ElementRef, private renderer: Renderer2) { }

  ngOnInit() {
    console.log('Directive called');
  }

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('blue');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }

  highlight(color: string) {
    this.renderer.setStyle(this.el.nativeElement, 'color', color);
  }

}
Run Code Online (Sandbox Code Playgroud)

我在 HTML 中使用它,如下所示:

<div class="container top-spacer">
  <div class="row text-center" >
    <div appEventhover class="col event" *ngFor="let event of eventList" (click)="storeEvent(event.job)">
      <img class="img-responsive" src="{{backendRoute}}/{{event.track_image_off}}">
      <p > {{event.name}} </p>
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

但是,它不起作用。它甚至不会吐出任何错误,也不会吐出任何其他内容。我可能做错了什么?

预先感谢您的帮助。

小智 5

只是为了添加已经提供的答案并分享我从经验中学到的东西。指令和要使用它的组件必须包含在同一模块中。请参阅下面的说明。

假设您有两个模块 A 和 B,分别包含组件 Ac 和 Bc,然后是指令 D。要在 Ac 中使用 D,D 和 Ac 都必须包含在模块 A 中,也就是说,无论包含 Ac,D 都必须包含为出色地。

至于Bc,因为D已经包含在模块A中,所以不能再次包含在模块B中,否则会出现多重声明错误,但此时D仍然不会对Bc生效。

Bc 的解决方案意味着将 D、Ac 和 Bc 移动到一个共享模块,其中这三个模块可以包含在一个位置。

我所说的包含是指与下面的示例类似的内容。另请注意,该解决方案基于 Angular 5

@NgModule({
    imports: [
       ***
    ],
    declarations: [**your directive and component**],
    providers: [***],
})
Run Code Online (Sandbox Code Playgroud)