概述

运行时动态改变组件模版的内容。没路由那么复杂,只是一段html,没有业务逻辑。

ngcontent指令将父组件模版上的任意片段投影到子组件上。

一、简单例子

1、子组件中使用<ng-content>指令来标记投影点

<div class="wrapper">
  <h2>我是子组件</h2>
  <div>这个div定义在子组件中</div>
  <ng-content></ng-content> 
</div>

2、父组件中把要投影到子组件的投影点的html片段写到子组件的标签中

<div class="wrapper">
  <h2>我是父组件</h2>
  <div>这个div定义在父组件中</div>
  <app-child2>
    <div>这个div是父组件投影到子组件中</div>
  </app-child2>
</div>

效果:

子组件加样式:

.wrapper{
    background: lightgreen;
}

父组件加样式:

.wrapper{
    background: cyan;
}

二、多个<ng-content>投影点

子组件:

<div class="wrapper">
  <h2>我是子组件</h2>
  <ng-content selecter=".header"></ng-content>
  <div>这个div定义在子组件中</div>
  <ng-content selecter=".footer"></ng-content> 
</div>

父组件:

<div class="wrapper">
  <h2>我是父组件</h2>
  <div>这个div定义在父组件中</div>
  <app-child2>
    <div class="header">这是页头,这个div是父组件投影到子组件中,title是{{title}}</div>
    <div class="footer">这是页脚,这个div是父组件投影到子组件中</div>
  </app-child2>
</div>

页头和页脚被投影到子组件中,同时title也被投影过去。

父组件模版中投影内容中插值表达式只能绑定父组件中的属性,虽然内容会被投影到子组件中去。

三、angular属性绑定的方式插入html

在父组件模版中加一行:

<div [innerhtml]="divcontent"></div>

父组件中加一个divcontent属性,内容就是一段html片段。

divcontent="<div>属性绑定绑innerhtml</div>";

效果

四、对比ngcontent指令和属性绑定innerhtml方式

[innerhtml]是浏览器特定的api。

ngcontent指令平台无关。可绑定多个投影点。

优先考虑ngcontent指令

以上就是详解angular组件之投影的详细内容,更多关于angular组件之投影的资料请关注www.887551.com其它相关文章!