zl程序教程

您现在的位置是:首页 >  前端

当前栏目

Angular ng-content元素的学习笔记

Angular笔记学习 元素 content NG
2023-09-14 09:04:03 时间

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的原创文章,尽在:“汪子熙”: