One day, I wrote a self-confident custom component myComponent, imported and used it on multiple pages, and the console gave me this
I have taken off my pants. What do you mean by this hint?
A closer look at The Component 'MyComponentComponent' is declared by more than one NgModule
what the hell? Say my component is used by multiple modules? What are you doing, I just want multiple pages to use! ! !
Usually the above error occurs because of the use of lazy loading routing (similar to the following)
const routes: Routes = [
...
{
path: 'first',
loadChildren: () => import('./com/first/first.module').then(m => m.FirstModule),//异步加载、惰性加载、懒加载
},
...
]
So I checked the official documentation and found a shared.module.ts stuff
First find a clean folder and create a
shared.module.ts
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { MyComponentComponent } from 'src/app/my-component/my-component.component';
// 这里加入自定义公共组件----------------------------------------
let declarations = [
MyComponentComponent,
];
@NgModule({
imports: [CommonModule,], //公共组件依赖的第三方组件可以在此处引入
declarations,
exports: declarations,
})
export class SharedModule { }
Go to the page Module file that needs to use the relevant public components
first.module.ts
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SharedModule } from '../../shared.module';
import { FirstComponent } from './first.component';
@NgModule({
imports: [
SharedModule,//这里引入公共组件模块(共享特性模块)
RouterModule.forChild([{ path: '', component: FirstComponent }]),//这句不加不会生效
],
declarations: [FirstComponent,]
})
export class FirstModule { }
first.component.html
first
<app-my-component></app-my-component>
second.module.ts
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SharedModule } from '../../shared.module';
import { SecondComponent } from './second.component';
@NgModule({
imports: [
SharedModule,//这里引入公共组件模块(共享特性模块)
RouterModule.forChild([{ path: '', component: SecondComponent }]),//这句不加不会生效
],
declarations: [SecondComponent,]
})
export class SecondModule { }
second.component.html
second
<app-my-component></app-my-component>
my-component.component.html
<h1>我特么终于没报错啦!</h1>
The routing is configured by itself, and you can directly access http://localhost:4200/first
Visit http://localhost:4200/second