假设现在我们有两个component:parentComponent和childComponent。
app.html 定义如下:
<parent>
<child></child>
<child></child>
</parent>
parentComponent定义如下:
@Component({
selector: 'parent',
templateUrl: 'parent.template.html'
})
export class UploadFormComponent{}
parent.template.html定义如下:
<label>parent:</label>
<ng-content></ng-content>
那么问题是:我们如何决定到底哪个child渲染到parent中呢?即替换ng-content。
- 如果
<ng-conent></ng-content>
不添加任何选择器,则两个都会被渲染到parent中。 - 如果
<ng-conent select=[selector]></ng-content>
存在select=[selector]选择器,其中[]意味着属性选择器。则只有存在selector属性的child会被渲染。如下所示:
<parent>
<child selector></child>
<child></child>
</parent>
- 如果
<ng-conent select=[selector=test]></ng-content>
存在select=[selector=test]选择器。则只有属性值为test的child会被渲染。
<parent>
<child selector="test"></child>
<child></child>
</parent>
- 如果
<ng-conent select=".selector"></ng-content>
存在select=”.selector”选择器。则只有存在.selector类样式的child会被渲染。
<parent>
<child class=".selector"></child>
<child></child>
</parent>
- 如果
<ng-conent select="selector"></ng-content>
存在select=”selector”选择器。则tag为selector的元素会被渲染。
<parent>
<child></child>
<selector></selector>
</parent>
既然我们可以为ng-content添加tag标签选择器,那么我们可以定义多个ng-content并决定哪部分被渲染到具体哪个位置。
parent.template.html定义如下:
<div>
<div class="header">
<ng-content select="header"></ng-content>
</div>
<ng-content select="body"></ng-content>
<div class="footer">
<ng-content select="footer"></ng-content>
</div>
</div>
app.html 定义如下:
<parent>
<header>
header
</header>
<body>
body
</body>
<footer>
footer
</footer>
<parent>