gpt4 book ai didi

angular - 如何为所有模块全局声明一个指令?

转载 作者:太空狗 更新时间:2023-10-29 16:54:56 24 4
gpt4 key购买 nike

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

最佳答案

根据@CrazyMac 的评论,一个好的方法是创建一个DirectivesModule。在这个模块中,您可以声明并导入所有指令,然后您就可以在任何您想要的地方导入这个模块。

app/modules/directives/directives.module.ts

import { NgModule } from '@angular/core';
import { HighlightDirective } from './highlight.directive';

@NgModule({
imports: [],
declarations: [HighlightDirective],
exports: [HighlightDirective]
})
export class DirectivesModule { }

app/modules/directives/highLight.directive.ts

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

@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}

app/modules/otherModule/other-module.module.ts

import { DirectivesModule } from '../directives/directives.module';

@NgModule({
imports: [
DirectivesModule
],
declarations: []
})
export class OtherModule { }

关于angular - 如何为所有模块全局声明一个指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41505392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com