我正在开发一个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资源库中自行查看、安装和测试.

推荐答案

如果您需要使用指令

@Directive({
  selector: '[appMyCommon]'
})
export class MyCommonDirective{}

你应该在任何地方创建一个新模块.

如果使用Angular CLI,则可以生成:

ng g module my-common

该模块:

@NgModule({
 declarations: [MyCommonDirective],
 exports:[MyCommonDirective]
})
export class MyCommonModule{}

重要的exports允许您在模块外使用指令.

最后,在需要使用指令的每个模块中导入该模块.

例如:

@NgModule({
  imports: [MyCommonModule]
})
export class AppModule{}

示例:Plunker

Angular相关问答推荐

为什么我的自定义.d.ts不起作用?LeaderLine不是构造函数

如何用ANGLE指令覆盖Html元素的数据绑定属性

CDK虚拟滚动由于组件具有注入属性而在滚动时看到错误的值

如何将管道异步化添加到不在html模板中的观察对象的Angular ?

我正在try 将一个带有模块联盟的Angular 8项目expose 到另一个Angular 项目,Angular 是15,这可能吗?如果是这样,有什么建议吗?

元素上的Angular 管道链接不起作用

使用Dragula时,ReactiveForm元素在拖动副本中显示不同的