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

ng2投影,父组件向子组件投影代码片段。

发布时间:2020-12-17 09:36:07 所属栏目:安全 来源:网络整理
导读:描述,组件复用,在父组件中,使用标签,引入子组件,一般情况,不会再标签之中,书写代码,或者书写“加载中...",当子组件代码渲染完毕以后就会替换掉这些代码,但是,如果想把父组件中的代码片段通过这样的形式传递给子组件,然后根据子组件的布局显示到

描述,组件复用,在父组件中,使用标签,引入子组件,一般情况,不会再标签之中,书写代码,或者书写“加载中...",当子组件代码渲染完毕以后就会替换掉这些代码,但是,如果想把父组件中的代码片段通过这样的形式传递给子组件,然后根据子组件的布局显示到界面上,就要使用到投影了,具体步骤如下:

1、定义子组件模板 child.component.html

<h4>子组件</h4>
<!-- 使用ng-content标记子组件位置,使用select区分不同的ng-conent -->
<!-- 使用标签形式 -->
<ng-content select="header"></ng-content>
<ng-content select="content"></ng-content>
<ng-content select="footer"></ng-content>
<!-- 使用class形式 -->
<ng-conent select=".class-select"></ng-content>

2、定义子组件 child.component.ts

import {Component} from "@angular/core";
@Component({
  selector: "child",templateUrl: "../templates/child.component.html"
})
export class AboutComponent {
  constructor() {
    console.log("child");
  }
}

3、定义父组件 home.component.ts

import {Component} from "@angular/core";
@Component({
  selector: "my-home",templateUrl: "../templates/home.component.html"
})
export class HomeComponent {
  name: string = "zxc";
  constructor() {
    console.log("home");
  }
}

4、定义组件模板 home.component.html

<my-contact>
  <!--这是传递给子组件的内容-->
  <header><h4>传递过来的内容,ng-content接受,{{name}}</h4></header>
  <footer>底部</footer>
  <div class="class-select>class传递信息</div>
</my-contact>

(编辑:李大同)

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

    推荐文章
      热点阅读