【发布时间】:2020-02-03 07:01:02
【问题描述】:
我创建了功能模块 将一个名为 HighlightDirective 的指令添加到 FeatureModule。在 AppModule 中使用 FeatureModule 的指令。如果将此指令用于 para,则 para 元素上发生 mouseenter 事件时 para 的背景色应变为蓝色,而当 mouseleave 事件发生时则无背景色。如果我使用 HighlightDirective 到 FeatureModule 它不起作用。但如果我将 HighlightDirective 用于 appModule,它就可以工作。
我的代码如下。
feature.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HighlightDirective } from '../highlight.directive';
@NgModule({
declarations: [HighlightDirective],
imports: [
CommonModule
]
})
export class FeatureModule { }
highlight.directive.ts
import { Directive, ElementRef, Renderer2, OnInit, HostListener, HostBinding, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(
private elementRef:ElementRef,
private renderer:Renderer2) { }
ngOnInit(){
this.color = this.defaultColor;
}
@Input() defaultColor;
@Input() highlight: string= 'lime';
@HostBinding('style.color') color:string = this.defaultColor;
@HostListener('mouseenter') mouseover(){
console.log('mouseover');
this.renderer.setStyle(this.elementRef.nativeElement, 'background-color', 'blue');
this.color=this.highlight;
}
@HostListener('mouseleave') mouseleave(){
this.renderer.setStyle(this.elementRef.nativeElement, 'background-color', 'transparent');
this.color=this.defaultColor;
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FeatureModule } from './feature/feature.module';
//import { TestDirective } from './test.directive';
@NgModule({
declarations: [
AppComponent,
// TestDirective,
],
imports: [
BrowserModule,
AppRoutingModule,
FeatureModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
appcomponent.html
<p appHighlight defaultColor="gray">Start editing to see some magic happen</p>
<router-outlet></router-outlet>
【问题讨论】:
-
如果您打算在应用程序和功能模块中使用共享模块,最好使用带有指令的共享模块。
-
请检查我更新的代码@the_mishra