搜尋
首頁web前端js教程聊聊angular中進行內容投影的方法

聊聊angular中進行內容投影的方法

May 12, 2022 am 10:41 AM
angularangular.js

這篇文章帶大家聊聊angular中的內容投影,介紹一下使用ng-content進行內容投影的方法,並了解有條件內容投影的實現方法,希望對大家有所幫助!

聊聊angular中進行內容投影的方法

一、 ng-content 進行內容投影

1.1 <span style="font-size: 16px;">ng-content</span>

ng-content 元素是用來插入外部或動態內容的佔位符。父元件將外部內容傳遞給子元件,當Angular 解析範本時,就會在子元件範本中ng-content 出現的地方插入外部內容。 【相關教學推薦:《angular教學》】

我們可以使用內容投影來建立可重複使用的元件。這些組件有相似的邏輯和佈局,並且可以在許多地方使用。一般我們在封裝一些公共元件的時候常常會用到。

1.2 為什麼要使用內容投影

定義一個button 元件:

button-component.ts

@Component({
    selector: &#39;[appButton]&#39;,
    template: `
    <span class="icon-search"></span>
`
})
export class AppButtonComponent {}

這個button 元件的目的是在按鈕內部加上一個搜尋的圖標,我們實際使用如下:

<button appButton>click</button>

我們發現元件只會展示搜尋圖標, 按鈕的文字不會展示,能你會想到最常使用的@Input 裝飾器,但是如果我們不只是想傳文字進來,而是傳一段html 進來呢?此時就會用到 ng-content

1.3 單一插槽內容投影

#內容投影的最基本形式是單一插槽內容投影

單插槽內容投影是指建立一個元件,我們可以在其中投影一個元件。

以button 元件為例,建立一個單槽內容投影:

button-component.ts

@Component({
    selector: &#39;[appButton]&#39;,
    template: `
    <span class="icon-search"></span> <ng-content></ng-content>
`
})
export class AppButtonComponent {}

實際使用如下:

<button appButton>click</button>

可以發現,現在這個button 元件的效果是即顯示了搜尋圖標,又顯示了按鈕的文字(click)。即把<button appbutton></button> 中間的內容投影 到了組件的<ng-content></ng-content>位置。

ng-content 元素是一個佔位符,它不會創建真正的 DOM 元素。 ng-content 的那些自訂屬性將被忽略。

1.4 多重插槽內容投影

#一個元件可以有多個插槽,每個插槽可以指定一個CSS 選擇器,該選擇器會決定要將哪些內容放入該插槽。此模式稱為多插槽內容投影。使用此模式,我們必須指定希望投影內容出現在的位置。可以透過使用 ng-contentselect 屬性來完成此任務。

  • 元件範本含有多個 ng-content 標籤。
  • 為了區分投影的內容可以投影到對應ng-content 標籤,需要使用ng-content 標籤上的select 屬性作為識別。
  • select 屬性支援標籤名稱屬性CSS 類別 :not 偽類別的任意組合。
  • 不新增 select 屬性的 ng-content 標籤將作為預設插槽。所有未配對的投影內容都會投影在該 ng-content 的位置。

以button 元件為例,建立一個多槽內容投影:

button-component.ts

@Component({
    selector: &#39;[appButton]&#39;,
    template: `
    <span class="icon-search"></span> <ng-content select="[shuxing]"></ng-content> <ng-content select="p"></ng-content> <ng-content select=".lei"></ng-content>
`
})
export class AppButtonComponent {}

實際使用如下:

<button appButton>
<p>click</p> <span shuxing>me</span> <span class="lei">here</span>
</button>

1.5 <span style="font-size: 16px;">ngProjectAs</span>

在某些情況下,我們需要使用ng-container 把一些內容包裝起來傳遞到元件中。大多數情況是因為我們需要使用結構型指令像 ngIfngSwitch 等。 。

在下面的範例中,我們將 header 包裹在了 ng-container 中。

@Component({
    selector: &#39;app-card&#39;,
    template: `
		<div class="card">
		  <div class="header">
		    <ng-content select="header"></ng-content>
		  </div>
		  <div class="content">
		    <ng-content select="content"></ng-content>
		  </div>
		  <div class="footer">
		    <ng-content select="footer"></ng-content>
		  </div>
		  <ng-content></ng-content>
		</div>
`
})
export class AppCardComponent {}

使用:

<app-card>
  <ng-container>
    <header>
      <h1 id="Angular">Angular</h1>
    </header>
  </ng-container>
  <content>One framework. Mobile & desktop.</content>
  <footer><b>Super-powered by Google </b></footer>
</app-card>

由於ng-container 的存在,header 部分並沒有被渲染到我們想要渲染的插槽中,而是渲染到了沒有提供任何selectorng-content 中。
在這種情況下,我們可以使用 ngProjectAs 屬性。
在上面的 ng-container 加上這個屬性,就可以按照我們的期望來渲染了。

<app-card>
  <ng-container ngProjectAs=&#39;header&#39;>
    <header>
      <h1 id="Angular">Angular</h1>
    </header>
  </ng-container>
  <content>One framework. Mobile & desktop.</content>
  <footer><b>Super-powered by Google </b></footer>
</app-card>

二、 有条件的内容投影

如果你的元件需要有条件地渲染内容或多次渲染内容,则应配置该元件以接受一个 ng-template 元素,其中包含要有条件渲染的内容。

在这种情况下,不建议使用 ng-content 元素,因为只要元件的使用者提供了内容,即使该元件从未定义 ng-content 元素或该 ng-content 元素位于 ngIf 语句的内部,该内容也总会被初始化。

使用 ng-template 元素,你可以让元件根据你想要的任何条件显式渲染内容,并可以进行多次渲染。在显式渲染 ng-template 元素之前,Angular 不会初始化该元素的内容。

2.1 <span style="font-size: 16px;">ng-container</span>

既不是一个组件,也不是一个指令,仅仅是一个特殊的tag而已。 使用 ng-container 渲染所包含的模板内容,不包含自身。

  • angular代码片段
<div>
  <ng-container>
    <p>My name is wyl.</p>
    <p>What is you name?</p>
  </ng-container>
</div>
  • 浏览器调试窗口,可以发现 <ng-container></ng-container> 标签消失了,并没有起任何作用
<div>
  <p>My name is wyl.</p>
  <p>What is you name?</p>
</div>
  • 使用场景,如下,在我们需要遍历if 判断 时,它可以承担一个载体的作用
<ul>
  <ng-container *ngFor="let item of items">
    <li>{{ item .name}}</li>
    <li>{{ item .age}}</li>
    <li>{{ item .sex}}</li>
  </ng-container>
</ul>

另外,ng 中常见错误之一的 forif 不能写在同一标签上(在一个宿主元素上只能应用一个结构型指令),利用 ng-container 标签可以在实现功能的基础上减少层级的嵌套。

2.2 <span style="font-size: 16px;">ng-template</span>

先来看下面一段代码

<ng-template>
    <p> In template, no attributes. </p>
</ng-template>

<ng-container>
    <p> In ng-container, no attributes. </p>
</ng-container>

浏览器输出结果是:

In ng-container, no attributes.

<ng-template></ng-template> 中的内容不会显示。当在上面的模板中添加 ngIf 指令:

<ng-template [ngIf]="true">
   <p> ngIf with a ng-template.</p>
</ng-template>

<ng-container *ngIf="true">
   <p> ngIf with an ng-container.</p>
</ng-container>

浏览器输出结果是:

ngIf with a ng-template.
ngIf with an ng-container.

2.3 <span style="font-size: 16px;">ng-template</span><ng-container></ng-container> 的配合使用

<ng-container *ngIf="showSearchBread; else tplSearchEmpty">
     暂时搜索不到您要的数据喔
</ng-container>
<ng-template #tplSearchEmpty>
     快快开始获取吧!
</ng-template>

2.4 <span style="font-size: 16px;">ngTemplateOutlet</span>

插入 ng-template 创建的内嵌视图。 ngTemplateOutlet 是一个结构型指令,接收一个 TemplateRef 类型的值;

<div *ngTemplateOutlet="tpl1"></div>
<ng-template #tpl1>
  <span>I am span in template {{title}}</span>
</ng-template>

*ngTemplateOutlet = "templateRefExp; content: contentExp "

  • templateRefExp: ng-template 元素的 #ID
  • contextExp:
    • 可空参数

    • content 是一个对象,这个对象可以包含一个 $implicitkey 作为默认值, 使用时在 模板 中用 let-key 语句进行绑定

    • content 的非默认字段需要使用 let-templateKey=contentKey 语句进行绑定

使用如下:

@Component({
  selector: &#39;ng-template-outlet-example&#39;,
  template: `
    <ng-container *ngTemplateOutlet="greet"></ng-container>
    <hr>
    <ng-container *ngTemplateOutlet="eng; context: myContext"></ng-container>
    <hr>
    <ng-container *ngTemplateOutlet="svk; context: myContext"></ng-container>
    <hr>
    <ng-template #greet><span>Hello</span></ng-template>
    <ng-template #eng let-name><span>Hello {{name}}!</span></ng-template>
    <ng-template #svk let-person="localSk"><span>Ahoj {{person}}!</span></ng-template>
`
})
class NgTemplateOutletExample {
  myContext = {$implicit: &#39;World&#39;, localSk: &#39;Svet&#39;};
}

2.5 利用 <span style="font-size: 16px;">ngTemplateOutlet</span> 进行内容投影

@Component({
    selector: &#39;app-card&#39;,
    template: `
		<div class="card">
		  <div class="header">
		  	<ng-container *ngTemplateOutlet="headerTemplate; context: { $implicit: title, index: otherDate }"></ng-container>
		  </div>
		</div>
`
})
export class AppCardComponent {

	@ContentChild(&#39;header&#39;, { static: true }) headerTemplate: TemplateRef<any>;

	public title = &#39;Test&#39;;
	public otherDate = {
	 	auth: &#39;me&#39;,
	 	name: &#39;appCard&#39;
	};
}

使用

<app-card>
  <ng-template #header let-label let-item="otherDate">
    <h1 id="Angular">Angular</h1> {{label}} (Test) and  {{otherDate | json}} ({auth: &#39;me&#39;, name: &#39;appCard&#39;})
  </ng-template>
</app-card>

更多编程相关知识,请访问:编程教学!!

以上是聊聊angular中進行內容投影的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript引擎:比較實施JavaScript引擎:比較實施Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

超越瀏覽器:現實世界中的JavaScript超越瀏覽器:現實世界中的JavaScriptApr 12, 2025 am 12:06 AM

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

使用Next.js(後端集成)構建多租戶SaaS應用程序使用Next.js(後端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:23 AM

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

如何使用Next.js(前端集成)構建多租戶SaaS應用程序如何使用Next.js(前端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:22 AM

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript:探索網絡語言的多功能性JavaScript:探索網絡語言的多功能性Apr 11, 2025 am 12:01 AM

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

JavaScript的演變:當前的趨勢和未來前景JavaScript的演變:當前的趨勢和未來前景Apr 10, 2025 am 09:33 AM

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

神秘的JavaScript:它的作用以及為什麼重要神秘的JavaScript:它的作用以及為什麼重要Apr 09, 2025 am 12:07 AM

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python還是JavaScript更好?Python還是JavaScript更好?Apr 06, 2025 am 12:14 AM

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。1.Python以简洁语法和丰富库生态著称,适用于数据分析和Web开发。2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器