我正在开发一个Github回购,它遵循官方教程的Angular (英雄之旅).您可以看到所有的代码here.
我的问题是,我在应用程序的主模块(app.module)中声明了一个指令,如果我在AppComponent
中使用它,它工作正常(该指令只高亮显示DOM元素中的文本).
但我有另一个模块叫做AppModule
中的HeroesModule
,在这个模块的一个组件中,这个指令不起作用.
主要代码如下:
app/app.module.ts个
...
import { HighlightDirective } from "./shared/highlight.directive";
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
InMemoryWebApiModule.forRoot(InMemoryDataService),
AppRoutingModule,
CoreModule,
HeroesModule
],
declarations: [
AppComponent,
HeroTopComponent,
HighlightDirective <-------
],
providers: [
{ provide: APP_CONFIG, useValue: AppConfig }
],
bootstrap: [ AppComponent ]
})
...
app/heroes/heroes.module.ts
@NgModule({
imports: [
CommonModule,
FormsModule,
HeroRoutingModule
],
declarations: [
HeroListComponent,
HeroSearchComponent,
HeroDetailComponent,
HeroFormComponent
],
providers: [
HeroService
],
exports: [
HeroSearchComponent
]
})
app/shared/highlight.directive.ts
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({ selector: '[tohHighlight]' })
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
app/app.component.ts
<h1 tohHighlight>{{title}}</h1> <----- HERE WORKS
<toh-nav></toh-nav>
<router-outlet></router-outlet>
app/heroes/hero-list/hero-list.component.ts
<div *ngIf="selectedHero">
<h2>
{{selectedHero.name | uppercase}} is my hero
</h2>
<p tohHighlight>Test</p> <----- HERE IT DOESN'T
<button (click)="gotoDetail()">View Details</button>
</div>
如果需要,您可以在Github资源库中自行查看、安装和测试.