繁体   English   中英

角度-在组件A内添加组件B

[英]Angular - Add component B inside component A

我的项目中具有以下结构,

src
- component-a
-- component-a.component.ts
-- component-a.html
-- component-a.scss
-- component-a.component.spec.ts

- component-b
-- component-b.component.ts
-- component-b.html
-- component-b.scss
-- component-b.component.spec.ts

- app.component.ts
- app.module.ts
- app.html

我在我的app.component.ts中使用了component-a ,因此已将其包含在app.module.ts的声明中。

declarations: [
        App, ComponentA,
    ],

并在app.html中: <component-a></component-a>

现在我想在我的component-a中添加component-b 因此,无论我尝试什么,当我在component-a.html中使用<component-b></component-b>都会出现此错误:

Unhandled Promise rejection: Template parse errors:
'component-b' is not a known element:
1. If 'component-b' is an Angular component, then verify that it is part of this module.
2. If 'component-b' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
      [ERROR ->]<component-b></component-b>
"): ng:///AppModule/ComponentA.html@7:6 ; Zone: <root> ; Task: Promise.then ; Value: 

如何在component-a.html中使用component-b?

  • 我尝试在component-a.component.ts中导入component-b
  • 我尝试在app.module.ts声明中导入并添加component-b。

正如我们在评论部分所讨论的。 您可以在app.module内部提供ComponentB以将其导入整个应用程序。

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

@NgModule({
  ...
  declarations: [
    AComponent, BComponent
  ]
})    
export class AppModule {}

http://plnkr.co/edit/H929znCRMcqlwuI4ySvp?p=preview

  1. 为两个组件创建一个模块。
  2. component B导入到component A的模块imports
  3. 完成。

示例(一个模块)

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

import {BModule} from '@components/b/b.module';

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

export class AModule {}

示例(B模块):

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

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

export class BModule {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM