【发布时间】:2017-05-21 04:45:07
【问题描述】:
我正在开发一个遵循 Angular(英雄之旅)官方教程的 Github 存储库。你可以看到所有的代码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 存储库中自行查看、安装和测试它。
【问题讨论】:
-
1.该指令应该属于一个模块 2。一种选择是您可以为所有指令创建一个单独的模块并将新的模块注入您的主应用程序模块
-
将其移至另一个模块(功能模块),然后将此模块添加到您要使用它的每个模块的
import: []。 -
@GünterZöchbauer 你是对的。例外的答案是错误的。您仍然不需要将它导入到您需要导出的每个模块中。只有注入器/服务被提升到根目录(除非懒惰)
-
我遇到的一个陷阱是,对模块结构的更改可能不会被“热”构建过程吸收。我通常使用 webpack 开发服务器(带有
@ngtools/webpack插件),我正在努力弄清楚为什么我的指令没有被应用。重新启动构建过程后,它立即生效。
标签: angular angular2-directives angular2-modules