Angular4学习笔记(八)- ng-content

内容投影

ng-content

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

以前举の例子,父组件包含子组件都是直接指明子组件的selector,比如子组件的selectorapp-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 元素的内容。

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

    <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 查询的元素

参考

原文地址:https://www.cnblogs.com/yw0219/p/7789211.html