【问题标题】:Using component encapsulated in a module from other module in angular 4使用 Angular 4 中其他模块封装在模块中的组件
【发布时间】:2017-09-03 09:49:58
【问题描述】:

我正在开发一个 Angular 4 应用程序,我有两个模块,第一个模块封装了一些我需要在其他模块中使用的功能。例如,我有第一个名为 SRModule 的模块,我已经导入了 SrCrComponent 组件:

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

// module imports
import { SrCrComponent} from './sr-cr';

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

我想在另一个模块的其他组件中使用 SrCrComponent,但我可以弄清楚如何使用。

在我的第二个模块 ReportsModule 中,我已在其上导入了 SRModule

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CPComponent } from './cp/cp.component';
import { SRModule } from "../sr-module/sr.module";

@NgModule({
  imports: [
    CommonModule,
    SRModule
  ],
  declarations: [
    CPComponent
  ]
})
export class ReportsModule { }

我的问题是,如何使用在 ReportsModule 上的 CPComponent 中声明的 SrCrComponent 组件?

这是我的 CPComponent ts 文件:

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-chart-period',
  templateUrl: './chart-period.component.html',
  styleUrls: ['./chart-period.component.css']
})
export class CPComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
}

在我的 CPComponent 的 html 中,我有一个 sr-gg 组件但无法正常工作,

<h2> Bar Chart</h2>
<sr-gg></sr-gg>

在 ReportsModule 中显然 'sr-g' is not a known element,事实上,这是控制台显示给我的错误,但我不知道我需要在哪里声明或在导入 SrCrComponen 时应该继承它。

【问题讨论】:

  • 您是否在组件中添加了选择器sr-cr,否则一切似乎都很好,应该可以工作
  • 请在此处添加您的SrCrComponent
  • 我在我的代码示例中修复了一些不好的名称,我删除了一些声明并减少了组件名称的长度以简化示例
  • 您在哪个组件中添加了选择器sr-gg
  • @BabarBilal in CPComponent

标签: javascript angular angular-components angular-module ng-modules


【解决方案1】:

ReportsModule 导入 SRModule 以及导出中指出的 SRModule 中的所有内容:[] 在您的情况下是 SrCrComponent。我假设 CpComponent 应该是 ReportsModule 的一部分,即 CpComponent 应该在声明中提到:[] for ReportsModule。你提到 sr-gg 作为一个组件,所以如果应该在 SrModule 中声明,那么导出应该看起来像导出:[SrCrComponent, SrGGComponent]

 @NgModule({
      imports: [
         CommonModule
      ],
      exports: [
         SrCrComponent, SrGGComponent
      ],
      declarations: [
        SrCrComponent, SrGGComponent
      ]
})
export class SRModule {}

    @NgModule({
      imports: [
        CommonModule,
        SRModule
      ],
      declarations: [
        ReportsComponent,
        ChartPeriodComponent,
        ChartSegmentationComponent,
        CpComponent
      ]

})

export class ReportsModule { }

那么它应该可以工作

【讨论】:

    猜你喜欢
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 2021-11-09
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多