简体   繁体   English

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

[英]Angular - Add component B inside component A

I have the following structure in my project, 我的项目中具有以下结构,

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

I'm using component-a inside my app.component.ts, so I have included it in declarations in the app.module.ts. 我在我的app.component.ts中使用了component-a ,因此已将其包含在app.module.ts的声明中。

declarations: [
        App, ComponentA,
    ],

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

Now I want to add component-b inside my component-a . 现在我想在我的component-a中添加component-b So whatever I tried, when I use <component-b></component-b> inside component-a.html I get this error: 因此,无论我尝试什么,当我在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: 

How do use component-b in component-a.html? 如何在component-a.html中使用component-b?

  • I tried importing component-b in component-a.component.ts 我尝试在component-a.component.ts中导入component-b
  • I tried importing and adding component-b in the app.module.ts declarations. 我尝试在app.module.ts声明中导入并添加component-b。

As we've discussed in the comment section. 正如我们在评论部分所讨论的。 You can provide ComponentB inside your app.module to import it throughout your app. 您可以在app.module内部提供ComponentB以将其导入整个应用程序。

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

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

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

  1. Create a module for both components. 为两个组件创建一个模块。
  2. Import component B into component A 's module imports . component B导入到component A的模块imports
  3. Done. 完成。

Example (A Module) 示例(一个模块)

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

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

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

export class AModule {}

Example (B Module): 示例(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