gpt4 book ai didi

javascript - Angular 惰性模块中的共享组件

转载 作者:行者123 更新时间:2023-12-02 22:28:29 25 4
gpt4 key购买 nike

我遇到了问题,但我不知道我没有看到什么。

我有Equis模块

ComponentsHomeModule,一个我想要共享的组件的文件

import { NgModule } from '@angular/core';
import { ElementComponent } from './element/element.component';
import { CommonModule } from '@angular/common';

@NgModule({
imports: [CommonModule],
declarations: [ElementComponent],
exports: [ElementComponent],
})
export class ComponentsHomeModule {}

在本例中,组件是 ElementComponent,这就是我要共享的组件。

然后我有我的 ElementsModule,我想在其中使用 ElementComponent

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { ElementsRoutingModule } from './elements-routing.module';
import { ElementsComponent } from './elements.component';
import { ComponentsHomeModule } from '../../components/components-home.module';

@NgModule({
imports: [CommonModule, ComponentsHomeModule, ElementsRoutingModule],
declarations: [ElementsComponent],
})
export class ElementsModule {}

然后在 ElementsComponent 内部,我尝试渲染 ElementComponent,但是当我在 html 中制作时

ElementsComponent html:
<app-element></app-element>

在控制台中我看到错误

ERROR in src/app/home/pages/elements/elements.component.html:15:7 - error TS8001: 'app-element' is not a known element:
1. If 'app-element' is an Angular component, then verify that it is part of this module

我不知道错误在哪里,因为如果我将组件导入并导出到 ComponentsHomeModule 中,然后导入该模块,则所有组件都应该可以工作。

顺便说一句,我尝试将 ComponentsHomeModule 导入到 App.Module 中,但没有任何结果,并且我使用 ComponentsHomeModule 的模块用于延迟加载:

import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home.component';
import { ElementsRoutingModule } from './pages/elements/elements-routing.module';

const routes: Routes = [
{
path: '',
component: HomeComponent,
children: [
{
path: '',
redirectTo: 'elements',
},
{
path: 'elements',
loadChildren: () => ElementsRoutingModule,
}
],
},
];

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

已解决::

问题出在延迟加载的导入上。

我导入的是 RoutingMoudule 而不是仅导入模块

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home.component';
import { ElementsModule } from './pages/elements/elements.module';

const routes: Routes = [
{
path: '',
component: HomeComponent,
children: [
{
path: '',
redirectTo: 'elements',
},
{
path: 'elements',
loadChildren: () => ElementsModule,
}
],
},
];

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

最佳答案

您的ElementsComponentElementsModule的一部分,因此如果您想在ComponentsHomeModule中使用ElementsComponent,那么您需要从 ElementsModule 导出 ElementsComponent,而不是从 ComponentsHomeModule

关于javascript - Angular 惰性模块中的共享组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58989403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com