首页 > 解决方案 > Angular 7 - 从导入的模块中获取组件

问题描述

我阅读了堆栈溢出向我展示的所有提出的问题,但都没有解决我的问题。

我是 Angular 的新手,我有几个ModulesComponents. 我想要一个子模块来导入一个组件。然后让父模块导入子模块并创建它的组件。是的,我已经在子模块中导出了组件

我想要这样:

但我得到了错误:

parent/parent.module.ts(8,5) 中的错误:错误 TS2304:找不到名称“ToyComponent”。

我不明白为什么这不起作用。我将不胜感激一些示例代码的解释。谢谢!


这是相关代码:

玩具组件

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-toy',
  templateUrl: './toy.component.html',
  styleUrls: ['./toy.component.css']
})
export class ToyComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

玩具组件 HTML

<p>
  Awesome toy!
</p>

子模块

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ToyComponent } from './toy/toy.component';
import { ChildComponent } from './child.component';

@NgModule({
  declarations: [
    ToyComponent,
    ChildComponent
  ],
  imports: [
    CommonModule
  ],
  exports: [
    ToyComponent
  ]
})
export class ChildModule { }

父模块

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ChildModule } from './child/child.module';
import { ParentComponent } from './parent.component';

@NgModule({
  declarations: [
    ToyComponent,
    ParentComponent
  ],
  imports: [
    ChildModule,
    CommonModule
  ],
  exports: [
  ]
})
export class ParentModule { }

父组件 HTML

<p>
  parent works! Child: Toy: <app-toy></app-toy>
</p>

标签: javascriptangularangular7angular-componentsangular-module

解决方案


修复:
1.ToyComponentParentModule.
2. 声明ToyComponentChild Module导出。
3.ChildModule作为导入添加到您的父模块。

原因
YourToyComponent是在 your 下声明的ChildModule。由于您ToyComponent在您的中使用ParentModule,您需要ToyComponent从您的ChildModule. 并ChildModule在您的ParentModule.


推荐阅读