Angular ng-content元素的学习笔记
ng-content 的select 屬性其實和 css 選擇器的工作方式類似,用于幫助 Angular 找到投影內容在 DOM 中的正確放置位置。
我個人把ng-content理解成Component工廠,能根據用戶指定的配置信息,動態生成Component,即configurable Component,這種行為稱之為Content Projection.
They are used to create configurable components. This means the components can be configured depending on the needs of its user. This is well known as Content Projection. Components that are used in published libraries make use of ng-content to make themselves configurable.
看一個例子:
project-content footer區域的div里定義了ng-content.
客戶如何將自己的UI內容注入到project-content中?
運行時,上圖的div元素,會被渲染到project-content Component的ng-content標簽內。
看一個更復雜一些的例子:
ng-content的select屬性值,決定了具體哪些UI內容會被注入到ng-content里。
Here we have first select to render header h1 element. If the projected content has no h1 element it won’t render anything.
第一個select會渲染h1元素,如果被注入的內容中并沒有h1元素,則Angular不會進行內容注入。
Similarly the second select looks for a div.
The rest of the content gets rendered inside the last ng-contentwith no select.
剩下的所有內容都被注入到最后一個不含select屬性的ng-content中去。
消費該project-content的例子:
更多Jerry的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的Angular ng-content元素的学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Flutter学习】之动画实现原理浅析
- 下一篇: [windows] Windows 激活