【问题标题】:How to add a component in sub module instead of AppModule?如何在子模块而不是 AppModule 中添加组件?
【发布时间】:2018-10-15 23:55:58
【问题描述】:

参考答案:Angular 5, using a component in a sub-module 但这对我的问题没有帮助。

我在AppModule 下有一个子模块PagesModule。我在PagesModule 中导入了一个组件,如下:

@NgModule({
  imports: [
    PagesRoutingModule,
    ECommerceModule,
  ],
  declarations: [
    AdvertisementComponent,
  ],
  providers: [ModuleService],
})

组件:

@Component({
  selector: 'ngx-advertisement',
  templateUrl: './advertisement.component.html',
  styleUrls: ['./advertisement.component.scss']
})
export class AdvertisementComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

应用模块:

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    AppRoutingModule,
    NgbModule.forRoot(),
    ThemeModule.forRoot(),
    CoreModule.forRoot(),
  bootstrap: [AppComponent],
  providers: [
    {provide: APP_BASE_HREF, useValue: '/'},
    {provide: HTTP_INTERCEPTORS, useClass: NbAuthJWTInterceptor, multi: true},
    AuthGuard,
  ],
})
export class AppModule {
}

AppRoutingModule:

const routes: Routes = [
  { path: 'pages', loadChildren: 'app/pages/pages.module#PagesModule' },
  { path: 'auth', loadChildren: 'app/auth/auth.module#AuthModule' },
  { path: '', redirectTo: 'pages', pathMatch: 'full' },
  { path: '**', redirectTo: 'pages' },
];

const config: ExtraOptions = {
  useHash: true,
};

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

我在ECommerceComponent 模板中使用AdvertismenetComponent 选择器,该模板添加到ECommerceModule 中,该模板位于PagesModules 中。

但我收到以下错误:

'ngx-advertisement' 不是已知元素:

【问题讨论】:

  • 我认为您应该显示应用程序的模块结构,并指出该组件在哪个模块中声明,以及您尝试在哪个模块中使用它。这将有助于我们为您提供帮助。
  • @ConnorsFan 我添加了模块的结构。谢谢

标签: angular


【解决方案1】:

如果你想在他的模块之外使用一个组件,你也需要导出它。

@NgModule({
  imports: [
    PagesRoutingModule,
    ECommerceModule,
  ],
  declarations: [
    AdvertisementComponent,
  ],
  exports: [AdvertisementComponent],
  providers: [ModuleService],
})

【讨论】:

  • 我仍然遇到同样的错误。你认为它正在使用外部模块吗?我在ECommerceModule 下有EcommerceComponent,而ECommerceModulePagesModule 下?
  • 您是否将 PagesModule 导入到 ECommerceModule 中?
  • 反之亦然。 ECommerceModule 在 PagesModule 中导入。
  • 如果在一个模块(M1)中,您想使用在另一个模块(M2)中声明的组件(C),则需要将M2导入M1。 M2 必须声明和导出 C。
  • core.js:1673 错误错误:未捕获(承诺中):错误:模块“ECommerceModule”导入的意外值“未定义”错误:模块“ECommerceModule”导入的意外值“未定义”
【解决方案2】:

我认为更好的解决方案是共享模块。

广告模块

import {NgModule} from '@angular/core';
import {AdvertisementComponent} from './advertisement.component';


@NgModule({
  imports: [],
  declarations: [
    AdvertisementComponent,
  ],
  exports: [
    AdvertisementComponent,
  ],
})

export class AdvertisementModule {
}

并在其他模块中导入

这解决了两个问题:两个模块中的组件和未知元素问题。

这最适合延迟加载。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2013-05-04
    • 2021-08-15
    • 2018-07-21
    • 2020-12-21
    • 2018-02-10
    • 2018-11-10
    相关资源
    最近更新 更多