Angular2访问子模块组件
我有一个带有子模块的Angular2应用程序:Angular2访问子模块组件,angular,import,module,components,Angular,Import,Module,Components,我有一个带有子模块的Angular2应用程序: ├───app (module) │ ├───authentication (module) │ │ ├───components │ │ │ ├───login │ │ │ ├───sign-in │
├───app (module)
│ ├───authentication (module)
│ │ ├───components
│ │ │ ├───login
│ │ │ ├───sign-in
│ │ │ ├───sign-up
│ │ │ ├───socials-callback
│ │ │ └───socials-sign-in
│ │ ├───models
│ │ └───services
│ ├───components
│ │ └───nav-bar
│ ├───home (module)
│ ├───shared (module)
│ │ ├───components
│ │ │ └───search-dropdown
│ │ └───services
│ └───user (module)
│ ├───models
│ └───services
每个组件都在module\u name.module.ts
文件(其模块)中声明。
每个模块文件都导入到app.module.ts
文件中
这是我的app.module.ts
文件:
import { BrowserModule } from '@angular/platform-browser';
import ...
import { SharedModule } from './shared/shared.module';
@NgModule({
imports: [
AppRoutingModule,
...
SharedModule
],
declarations: [
AppComponent
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
import { NgModule } from '@angular/core';
import ...
import { SearchDropdownComponent } from './components/search-dropdown/search-dropdown.component';
@NgModule({
imports: [
CommonModule
],
declarations: [
SearchDropdownComponent
]
})
export class SharedModule { }
我的shared.module.ts
文件:
import { BrowserModule } from '@angular/platform-browser';
import ...
import { SharedModule } from './shared/shared.module';
@NgModule({
imports: [
AppRoutingModule,
...
SharedModule
],
declarations: [
AppComponent
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
import { NgModule } from '@angular/core';
import ...
import { SearchDropdownComponent } from './components/search-dropdown/search-dropdown.component';
@NgModule({
imports: [
CommonModule
],
declarations: [
SearchDropdownComponent
]
})
export class SharedModule { }
当我尝试从我的应用程序模块的模板访问SearchDropdownComponent时,我有一个错误,告诉我没有对应的组件
但是,当我直接在app.module.ts文件中添加SearchDropdownComponent导入时,它就起作用了
难道不能访问子模块的组件吗?
我做错了什么?要使组件在模块外部可用,请将其添加到模块的
导出
声明中
import { NgModule } from '@angular/core';
import ...
import { SearchDropdownComponent } from './components/search-dropdown/search-dropdown.component';
@NgModule({
imports: [
CommonModule
],
declarations: [
SearchDropdownComponent
],
exports: [
SearchDropdownComponent
]
})
export class SharedModule { }
API参考:
另请注意,一个组件只能属于一个模块。这是否意味着如果我有一个模块
a
和两个子模块B
和C
,如果我在模块a
中导出B
组件,它就不能在模块C
中使用?您可能是在引用该语句“一个组件只能属于一个模块”-没错。这意味着组件x
可以“属于”(出现在声明中)模块A、B或C中的任何一个。但这与能否使用它无关-要在另一个模块中使用组件x
,您需要导入导出组件x
的模块。假设您要使用在模块B中声明的组件。您从B导出它,然后在模块A和C中导入模块B。存在相同的问题,应用了此修复程序,它成功了。但是,为什么有必要在导出
中复制声明
?这是一种性能优化吗?@AdrianMoisa,例如,您可能希望在模块内部有一些组件-在这种情况下,您不会将它们添加到导出
,这就是出现此问题的原因之一是单独的属性。@RonaldZarīt您的意思是类似于类方法的public/private?