Angular 5,如何在子模块中使用组件

3
我遇到了一个错误,我似乎无法解决。当我将我的应用程序细分为懒加载效率,并使用子路由器进行 "child" 时,我需要使用在主应用程序中使用的组件。
但是我得到了以下错误消息:
“Type AccountInfoComponent is part of the declarations of 2 modules”
我的应用程序结构如下:
app
|--components
    |--accountInfo
        |--accountInfo.component.ts
    |--user
        |--user.component.ts
|--modules
    |--child
        |--child.component.ts
        |--child.module.ts
        |--child.routing.module.ts
|--app.module.ts
|--app.routing.module.ts

在主模块中声明了AccountInfoComponent(它没有被导入到主路由器中,而是通过其选择器调用...)

所以我将我的“子”组件移动到自己的模块中,包括一个(为子组件)设计的路由和延迟加载

我的"Child.router"如下所示

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { ChildComponent } from './child.component';
import { ChildProfileComponent } from './child.profile.component';

import { AccountInfoComponent } from '../../components/accountinfo/accountinfo.component';

const childRoutes: Routes = [
    {
        path: '', 
        component: ChildComponent,
        children: [
            {
                path: '',
                component: ChildProfileComponent
            },
            {
                path: 'account',
                component: AccountInfoComponent 
            }
        ]
    }
];

@NgModule({
    imports: [
        RouterModule.forChild( childRoutes )
    ],
    exports: [
        RouterModule
    ]
})
export class ChildRoutingModule {}

主要的app.module声明了AccountInfoComponent,因为它在user.component中被使用。

我尝试将AccountInfoComponent导入到子路由中,也尝试从主模块中导出它。

问题:如何在多个模块中使用组件?主应用程序和嵌套模块中都需要使用。


你想将它分解为另一个模块,然后在两个模块中引用。 - undefined
我很担心这个问题 - 我有一堆组件,它们需要成为自己的模块...这种情况常见吗? - undefined
1
是的,不幸的是这是相当常见的。NgModule是一个设计不佳的抽象化概念。 - undefined
1个回答

3

确实,您不能在多个模块中声明同一组件。

您可以创建一个共享模块,其中包含您想要在多个模块中重用的组件。

在您的示例中,此共享模块可以声明和导出AccountInfoComponent等其他需要在不同模块中重用的组件。

https://angular.io/guide/ngmodule-faq#sharedmodule

您可以在共享模块中声明多个组件,也可以为每个组件创建一个模块并有选择地导入它们,这就是Angular Material所做的(MatButtonModuleMatCheckboxModule,...)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接