1. 程式人生 > >Angular4-線上競拍應用-ngContent指令

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這種方式。