内容投影
ng-content

ng-content是一个占位符,有些相似于router-outlet。

以前举の例子,父组件蕴含子组件都是间接指明子组件的selector,比方子组件的selector叫app-child,那么嵌入父组件时间接指明即可:

<app-child></app-child>

这是很硬性的编码,而ng-content就是用来代替这种硬性编码的。

比方有个父组件这样定义:

@Component({
selector: 'app-parent',
template: `

<p>Parent Component</p><div style="background: cyan">  <ng-content></ng-content></div>

`
})

它示意被放进的内容的背景色对立设置为cyan。

接下来就要将子组件放入父组件中,搁置的形式很简略,在根组件中将app-child插入到app-parent中即可:

<app-parent>

<app-child></app-child>

</app-parent>

多个投影

上例中只有一个投影,那么多个投影怎么办呢?<ng-content>反对一个select属性,能够让你在特定的中央投射具体的内容。该属性反对 CSS 选择器(my-element,.my-class,[my-attribute],...)来匹配你想要的内容。如果ng-content上没有设置select属性,它将接管全部内容,或接管不匹配任何其余 ng-content 元素的内容。

示例:

http://www.developcls.com/qa/aa47c62122cd4fb7af18b0dc2131a3be.html

比方父组件上有两个可投影的地位,一个背景为浅绿,一个为粉红:

<div style="background: cyan">

  <ng-content select="[name=child]"></ng-content></div><div style="background: pink">  <ng-content select=".red"></ng-content></div>

此时能够在根组件上定义如下:

<app-parent>

  <app-child class="red"></app-child>  <app-child name="child"></app-child></app-parent>

这样就能够对号入座了!
ContentChild

了解了ng-content就能够应用@ContentChild装璜器来调用投影内容了,它和@ViewChild十分相似,就不多做介绍了,其异同点列举如下:

相同点

都是属性装璜器都有对应的复数模式装璜器:ContentChildren、ViewChildren都反对 Type|Function|string 类型的选择器

不同点

ContentChild 用来从通过 Content Projection 形式 (ng-content) 设置的视图中获取匹配的元素ViewChild 用来从模板视图中获取匹配的元素在父组件的 ngAfterContentInit 生命周期钩子中能力胜利获取通过 ContentChild 查问的元素在父组件的 ngAfterViewInit 生命周期钩子中能力胜利获取通过 ViewChild 查问的元素

参考

ng-content 中暗藏的内容Angular 2 ContentChild & ContentChildren