Angular 2 实现transclusion

假设现在我们有两个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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值