ng2投影,父組件向子組件投影代碼片斷。

描述,組件複用,在父組件中,使用標籤,引入子組件,通常狀況,不會再標籤之中,書寫代碼,或者書寫「加載中...",當子組件代碼渲染完畢之後就會替換掉這些代碼,可是,若是想把父組件中的代碼片斷經過這樣的形式傳遞給子組件,而後根據子組件的佈局顯示到界面上,就要使用到投影了,具體步驟以下:html

一、定義子組件模板 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>

二、定義子組件 child.component.tscode

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

三、定義父組件 home.component.tscomponent

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

四、定義組件模板 home.component.htmlhtm

<my-contact>
  <!--這是傳遞給子組件的內容-->
  <header><h4>傳遞過來的內容,ng-content接受, {{name}}</h4></header>
  <footer>底部</footer>
  <div class="class-select>class傳遞信息</div>
</my-contact>
相關文章
相關標籤/搜索