Angular4-在线竞拍应用-ngContent指令

ngContent指令

新建项目demo6

新建组件ng g component child

投影,在某些情况下,需要动态改变模板的内容,可以用路由,但路由是一个相对比较麻烦的东西,而我要实现的功能没有那么复杂,,没有什么业务逻辑,也不需要重用。

这个时候可以用投影。可以用ngContent将父组件中任意片段投影到子组件中

修改child.component.html

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

修改app.component.html

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

修改child.component.css

.wrapper{
  background:lightgreen;
}

修改app.component.css

.wrapper{
  background:cyan;
}

启动项目

这里写图片描述
一个组件可以在其模板中声明多个ng-content标签

假设子组件的部分是由三部分组成的,页头,页脚和内容区。页头和页脚由父组件投影进来,内容区自己定义

修改child.component.html

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

修改app.component.html

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

app.component.ts

export class AppComponent {
  title = 'app';
}

启动项目

这里写图片描述

使用的{{title}}只能绑定父组件中的属性。

Angular还可以用属性绑定的形式很方便的插入一段HTML。

修改app.component.html

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

<div [innerHTML]="divContent"></div>

修改app.component.ts

export class AppComponent {
  title = 'app';

  divContent="<div>慕课网</div>";
}

这里写图片描述

innerHTML这种方式只能在浏览器中使用,而ngContent是跨平台的,可以在app应用中使用

ngContent可以设置多个投影点,

动态生成一段HTML,应该优先考虑ngContent这种方式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值