gpt4 book ai didi

Angular 不适用于延迟加载的模块

转载 作者:行者123 更新时间:2023-12-04 02:05:59 26 4
gpt4 key购买 nike

我创建了一个在 app.component 上运行良好的自定义组件,但是当 <custom-component>在延迟加载模块中使用它会给出错误:

Error: Template parse errors:
'my-component' is not a known element:
1. If 'my-component' is an Angular component, then verify that it is part of this module.
2. If 'my-component' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

我正在使用 Angular 4.0.0/CLI

代码:

app.module.ts

...
import { LoaderComponent } from './shared/components/list-components/loader/loader.component';

@NgModule({
declarations: [
AppComponent,
LoaderComponent <- declared here because I need the component in multiple modules
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

loader.component.ts
import { Component, OnInit, Input, Output } from '@angular/core';

@Component({
selector: 'my-component',
templateUrl: './loader.component.html',
styleUrls: ['./loader.component.css']
})
export class LoaderComponent implements OnInit {
@Input() type:any;

constructor() { }

ngOnInit() {
}

}

应用程序路由.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [

{ path: 'lazy', loadChildren: './lazy/lazy.module#LazyModule' },

];

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

app.component.html
<router-outlet></router-outlet>
<my-component></my-component> <-- works here

和lazy.component.html
<p>
this module is lazy loaded
<my-component ></my-component> <- not working
</p>

有任何想法吗?

* 更新 *

我创建了一个声明 LoaderComponent 的 SharedModule。 SharedModule 被导入到每个需要 LoaderComponent 的模块中。作品!

最佳答案

您需要创建 LoaderModule:

@NgModule({
imports: [],
exports: [LoaderComponent],
declarations: [LoaderComponent],
providers: [],
})
export class LoaderModule {
}

然后将此模块添加到 app.module
@NgModule({
declarations: [
AppComponent,
],
imports: [
LoaderModule,
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

确保将 LoaderModule 也添加到 LazyModule

关于Angular <custom-component> 不适用于延迟加载的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43385299/

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