加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 08:40:09 所属栏目:安全 来源:网络整理
导读:ngContent指令 新建项目demo6 新建组件ng g component child 投影,在某些情况下,需要动态改变模板的内容,可以用路由,但路由是一个相对比较麻烦的东西,而我要实现的功能没有那么复杂,,没有什么业务逻辑,也不需要重用。 这个时候可以用投影。可以用ngC

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这种方式。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读