问题
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-list
component.
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