new*_*ser 15 typescript angular
所以,我创建了一个组件ExampleComponent和模块,在宣布它的心不是在app.module上市。接下来,我想声明组件ExampleComponent一个模块中被在app.module列出。我该怎么做呢?如果我简单地声明它,那么我会收到以下错误:组件ExampleComponent是由多个NgModule声明的。
abc.module.ts
import { ExampleComponent} from '../Example/Example.component';
@NgModule({
declarations: [
ExampleComponent
]
})
Run Code Online (Sandbox Code Playgroud)
app.module.ts
import { NewModule} from '../new/new.component';
@NgModule({
imports: [
NewModule
declarations: [
]
})
Run Code Online (Sandbox Code Playgroud)
新模块
import { ExampleComponent} from '../Example/Example.component';
@NgModule({
declarations: [
ExampleComponent
]
})
Run Code Online (Sandbox Code Playgroud)
Ami*_*ian 34
如果您在多个模块中使用您的组件,则表示该组件是共享的。您需要为您创建一个专用模块 ( ExampleModule
) ExampleComponent
,然后在您想要使用的任何地方导入该模块ExampleComponent
。
所以创建 ExampleModule:
import { NgModule } from '@angular/core';
import { ExampleComponent} from '../Example/Example.component';
@NgModule({
declarations: [
ExampleComponent,
],
exports: [
ExampleComponent,
]
})
export class ExampleModule { }
Run Code Online (Sandbox Code Playgroud)
然后将其导入到您想要使用的位置ExampleComponent
(进入abc module
和app module
),如下所示:
import { ExampleModule } from '../example.module';
@NgModule({
imports: [
ExampleModule
]
...
})
Run Code Online (Sandbox Code Playgroud)
通过为共享组件定义单独的模块,您提供了一些封装层,您可以在其中描述和提供组件运行所需的所有依赖项,因此,将来所有使用者只需导入模块本身即可了解有关所有这些依赖项的任何信息。
S J*_*ANA 13
如果在app.module.ts文件而不是模块文件中导入组件,则会出现此错误。
案例分析:
我的文件夹结构如下:
app
src
component
general.component.ts
general.component.html
general.component.scss
general.component.spect
general.module.ts
general.model.ts
general.services.ts
app.module.ts
app.routing.ts
Run Code Online (Sandbox Code Playgroud)
当以下情况发生时,会出现错误“该组件由多个 NgModule 声明”
如果您已按如下方式导入,则在 app.module.ts 文件中;
import { GeneralComponent } from './component/general/graph.component';
@NgModule({
declarations: [
GeneralComponent
],
})
Run Code Online (Sandbox Code Playgroud)
解决问题的改变
通用模块.ts
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { GeneralComponent } from './general.component'
@NgModule({
declarations: [GeneralModule.rootComponent],
imports: [CommonModule],
exports: [GeneralModule.rootComponent],
entryComponents: [GeneralModule.rootComponent],
})
export class GeneralModule {
static rootComponent = GeneralComponent
}
Run Code Online (Sandbox Code Playgroud)
应用程序模块.ts
import { GeneralModule } from './component/graph-general/graph-general.module';
@NgModule({
declarations: [
],
imports: [
GeneralModule ,
]
})
export class AppModule {
}
Run Code Online (Sandbox Code Playgroud)
注意:始终只有组件应该在声明中,所有模块都应该在导入中。
归档时间: |
|
查看次数: |
18265 次 |
最近记录: |