【发布时间】:2018-04-17 21:34:43
【问题描述】:
所以我最近开始学习 Angular。我已经到了要开始制作自定义指令的地步。经过一些研究,我发现只需几个步骤即可完成此操作。
- 创建指令
- 将其导入您的应用模块中
- 将其包含在应用模块声明数组中
- 在组件的模板中使用它
考虑到这一点,我着手创建一个自定义指令,它只会更改属性指令所附加到的元素的背景颜色。但是,我的指令似乎不起作用。 然后我尝试将它包含在我的路由模块中,然后指令起作用了......
为什么我必须将它包含在路由模块中?这感觉不太全局,我觉得我宁愿将它直接包含在根模块中,以便我可以在整个应用程序中使用该指令。如果我只将它包含在应用程序根模块中,它不应该仍然有效吗?
为指令创建一个单独的模块然后导出该模块并将其导入根模块中会更好吗?还是在我的路由模块中导入指令好吗?
更新
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
// Routing Module
import { AppRoutingModule } from './app-routing.module';
// app layout components
import { AppComponent } from './app.component';
import { AppNavbarComponent } from './components/app-navbar/app-navbar.component';
import { AppFooterComponent } from './components/app-footer/app-footer.component';
@NgModule({
declarations: [
AppNavbarComponent,
AppFooterComponent,
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
// Routing Components
import { AboutComponent } from './components/about/about.component';
import { HomeComponent } from './components/home/home.component';
import { PageNotFoundComponent } from './components/page-not-
found/page-not-found.component';
// Directives
import { TestDirective } from './directives/test/test.directive';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
declarations: [
AboutComponent,
HomeComponent,
PageNotFoundComponent,
TestDirective
],
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app-component.html
<app-navbar></app-navbar>
<router-outlet></router-outlet>
<app-footer></app-footer>
所以问题在于,如果我将其包含在 app-routing.module.ts 文件中,导航栏和页脚似乎无法访问该指令,但如果我将指令包含在 app.module.ts 文件中,则该指令似乎仅适用于导航栏和页脚,但不是任何单独的路线。显然我不能在两个模块中都包含该指令。
但是,我可以在应用程序的任何位置使用任何内置的角度指令,例如 ngIf。我希望我的指令具有相同的范围。
【问题讨论】:
-
不清楚为什么需要包含路由模块。发布代码可以使其更清晰。您不使用 Angular 导入导入指令),只导入模块。
-
@GünterZöchbauer 抱歉,您不清楚。我更新了问题以包含相关代码和对问题的更好解释。我已经取得了一些进展,感觉你的评论。希望有帮助
-
路由模块应该只包含路由相关的东西,应该在不同地方重用的组件和指令应该放在一个或多个共享模块中。指令和组件应列在声明和导出中。然后通过导入共享模块使共享模块的指令和组件对其他模块可用。 angular.io 有更多关于模块的信息。
-
感谢共享模块部分正是我最终需要的。