一、什么是自定义内容&作用
自定义内容通常是用来创建可以复用的组件,例如模态框,导航栏。这两个组件是经常要用到的,所以自定义内容就是为组件服用提供了便利,实现了组件的复用,从而减少了重复代码的编写。
二、怎样使用自定义内容
与自定义内容相关的标签:<ng-content>
现在以网页中的header为例,介绍如何使用ng-content
1.先创建组件用于header
1 import {Component} from "@angular/core"; 2 @Component({ 3 selector:'header-content', 4 template:`<div> 5 <h4>Example header with ng-content</h4> 6 <div style="background-color: green;padding:5px; margin: 2px;"> 7 <ng-content selector="header"></ng-content> 8 </div> 9 </div>` 10 }) 11 export class HeaderComponent{ 12 13 }
2.在定义一个简单的根组件去使用它
1 import {Component} from "@angular/core"; 2 @Component({ 3 selector:'app', 4 template:`<header-content> 5 <header>Header content</header>//此处将自定义的内容放到header-content标签之间 6 </header-content>` 7 }) 8 export class AppComponent{ 9 10 }
最后组件的DOM树会被Angular处理成以下:
<app>
<header-content>
<div>
<h4>Example Component with ng-content</h4>
<div style="background-color: green;padding:5px; margin: 2px;">
<header>Header content</header>
</div>
</div>
</header-content>
</app>
我们注意到,header-content标签之间的内容也就是<header>Header content</header>,被填充到了ng-content中去了,而HeaderComponent模版中的其他元素没有受到影响。之所以可以显示自定义的内容是因为,在ng-content中有select=“header”这个属性,这是一个选择器,它表示匹配header-content标签中第一个header标签,并将其填充到相应的ng-content中
自定义内容是可以显示多个内容的
在HeaderComponent中模版改成如下所示:
<div>
<h4>Example header with ng-content</h4>
<div style="background-color: green;padding:5px; margin: 2px;">
<ng-content selector="header"></ng-content>
</div>
<div style="background-color: green;padding:5px; margin: 2px;">
<ng-content selector=".class-select"></ng-content>
</div>
<div style="background-color: green;padding:5px; margin: 2px;">
<ng-content selector="#footer"></ng-content>
</div>
</div>
则在根组件中代码如下:
<header-content>
<header>Header content</header>//此处将自定义的内容放到header-content标签之间
<div class="class-select">div with .class-select</div>
<div id="footer">Footer content</div>
</header-content>
有了自定义内容,这样我们的很多组件都可以服用了