关于angular:Angular4学习笔记

4次阅读

共计 1425 个字符,预计需要花费 4 分钟才能阅读完成。

内容投影
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
正文完
 0