Angular: Custom Component in Custom Component

时间:2019-01-18 19:09:10

标签: angular components

After lots of searching: Is it possible to nest custom components in custom components?

I've created an empty angular cli - project and created ComponentAComponent (selector: 'componentA') and ComponentBComponent (selector: 'componentB').

My app.component.html looks like:

<componentA>
  <componentB></componentB>
  <componentB></componentB>
</componentA>
<componentB></componentB>

What I would expect:

Component A works!
Component B works!
Component B works!
Component B works!

But only

Component A works!
Component B works!

gets rendered. As I want to implement a custom list with custom list-items: What do I have to do to render custom components nested in custom components?

After a lot of google/ stackoverflow/ trial and error - grateful for any advice or link you can give me. Tried so much stuff with imports and declarations but nothing worked.

In case it helps I can provide a github repository with code.

Kind regards

EDIT: ABOS provided the correct answer. I added

<ng-content></ng-content>

to componentA.html and now all nested elements get rendered. So simple, but I did not find it. Thank you!

1 个答案:

答案 0 :(得分:1)

如果要动态添加html /组件,可以使用<ng-content>。有大量的教程,例如https://blog.angular-university.io/angular-ng-content/