为了重用一个组件,我试图将一个组件从一个模块移动到它的父组件而没有成功(多个子模块应该使用它)。
最初,子模块里面有以下代码(我想移动MyDesiredComponent
):
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ClickOutsideModule } from 'ng-click-outside';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { ChildComponent } from './child.component';
import { MyDesiredComponent } from '../common/timeline/timeline.component';
export const routes: Routes = [
{ path: 'child', component: ChildComponent },
];
@NgModule({
imports: [
CommonModule,
NgbModule,
RouterModule.forChild(routes),
FormsModule,
BrowserAnimationsModule,
ClickOutsideModule,
],
declarations: [
ChildComponent,
MyDesiredComponent
]
})
export class ChildModule { }
我将声明移到父模块中,如下所示:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ChildModule } from './child/child.module';
import { DesiredComponent } from './common/desired/desired.component';
@NgModule({
imports: [
ChildModule
],
declarations: [DesiredComponent],
exports: [DesiredComponent]
})
export class ParentModule { }
移动组件后,应用程序无法加载,出现以下错误:'desired-component' is not a known element
。
我在这里缺少什么?
答案 0 :(得分:2)
实现这一目标的最佳方法是通过"延迟加载"共享模块中的组件,并将其导入app.module.ts
中<强> shared.module.ts 强>
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { DesiredComponent } from '';
@NgModule({
imports: [CommonModule, RouterModule],
declarations: [DesiredComponent, LoadingComponent],
exports: [DesiredComponent,
CommonModule, FormsModule, RouterModule]
})
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: []
};
}
}
<强> app.module.ts 强>
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { SharedModule } from '';
import { AppComponent } from '';
@NgModule({
imports: [BrowserModule, SharedModule.forRoot()],
declarations: [AppComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }