How to use content projection (aka transclusion) in Angular

做~自己de王妃 提交于 2020-01-03 00:52:10

问题


I am new to angular 4.

I have a doubt in angular 4 embedded components.

example:

<hero-list>
    <hero></hero>
    <hero></hero>
</hero-list>

I wanted to know how to create a view based on this structure that is embedding component inside another component.


回答1:


You should use <ng-content></ng-content> in your hero-list-component. So you can realize your wish above.

hero-list.component.html

<div class="hero-list">
  <h1>Hero list</h1>
  <ng-content></ng-content>
</div>

And now you can wrap your hero-item-components and they will be printed inside of hero-listcomponent.

app.component.html

<hero-list>
  <hero-item></hero-item>
  <hero-item></hero-item>
</hero-list>

Here is working example: https://stackblitz.com/edit/angular-nvpmtc

And here is a good article about content projection in angualr.




回答2:


If you mean you want a master layout with sub views, you might want to look at the Angular router https://angular.io/tutorial/toh-pt5

Which might look something like this

<app-component>
  <h1>Static title</h1>
  <router-outlet></router-outlet>
</app-component>

The router-outlet will switch between different components defined in your routing file when navigating to different links, but the html around it won't change



来源:https://stackoverflow.com/questions/45752761/how-to-use-content-projection-aka-transclusion-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!