Angular 内容投影 content projection 关于选择器问题的单步调试
问题描述
我定义了一个能够允许消费者 Component 将其自定义内容通过 content projection
投射进来的 Component:
import { Component } from '@angular/core';
@Component({
selector: 'app-zippy-basic',
template: `
Default:
<ng-content></ng-content>
Question:
<ng-content select="[question]"></ng-content>
`
})
export class ZippyBasicComponent {}
其中包含 default
和 question
两个区域。
对于 question 区域而言,只有在消费 Component 提供的内容,满足第 10 行指定的选择器时,该内容才能被投影到 app-zippy-basic
内部。
我的消费代码如下:
<app-zippy-basic>
<p #question>
带了问号的 p 节点
</p>
<p>普通 p 节点</p>
</app-zippy-basic>
我期望的结果:
- 普通 p 节点,出现在 default 区域;
- 带了问号的 p 节点,出现在 question 区域。
实际测试结果:question 区域为空。
问题分析
根据 Angular 官网的定义,select="[question]" 的语法含义是,将消费 Component 中具有 question
的 attribute
的 dom 节点,投射到 app-zippy-basic
中。因此,第 23 行中的 #
应该去掉,这样才能产生一个具有 question
属性的 p 节点:
去掉之后,p 节点果然按照我们期望的那样,显示在 default
区域了:
我们再来通过单步调试的方式,找到带有 question
属性的 p 节点是如何被选择以及投射的。
Angular 框架内部维护了一个叫做 LView
即 Logic View
的数据结构,这是一个数组:
LView
的内容:
其中索引为 21 的数组元素,rawSlotValue
,存放的就是需要被投影到 question 区域,带有 question 属性的 p 节点。
总结
如果组件包含一个没有 select 属性的 ng-content
元素,则该实例会接收与任何其他 ng-content
元素都不匹配的所有投影组件。
逻辑视图 (LView) 表示模板 (TView) 的实例。 我们使用逻辑
这个词来强调开发人员如何从逻辑角度看待应用程序。 ParentComponent 包含一个 ChildComponent。 从逻辑的角度来看,我们认为 ParentComponent 包含 ChildComponent,因此称为逻辑
。 逻辑一词与渲染树的最终概念形成对比。
相关文章
- [ngx-formly] Dynamically hide Form Controls with Angular Formly
- [Angular 8] Keep original DOM structure with ng-container
- [Angular] Design API for show / hide components based on Auth
- [Angular] Show a loading indicator in Angular using *ngIf/else, the as keyword and the async pipe
- [Angular] Wrap a third party lib into service
- [Angular 2] Value Providers & @Inject
- SAP Spartacus 服务器端渲染单步调试步骤之二:在服务器端执行应用程序 Angular 代码
- 想调试Angular框架的@HostBinding,应该在哪里设置断点
- Angular 指令ngTemplateOutlet的运行原理单步调试
- 2020国庆节 Angular structual 指令学习笔记(<ng-template>) 包含语法糖解糖过程
- Angular页面里元素class的动态绑定的实现源代码调试
- 通过单步调试的方式学习 Angular 中带有选择器的内容投影使用方式
- 如何创建 Angular 库并在 Angular 应用里调用
- Angular里interpolation text节点的创建逻辑,单步调试
- 调试Angular指令实现时一个有用的内部属性:__ngContext__
- Angular sandbox项目的tsconfig.json内容一览
- Angular页面调试一个有用的小技巧 - normalizeDebugBindingName和normalizeDebugBindingValue - [object Object]
- Angular reducer第一次被框架调用的单步调试细节
- Angular父子Component之间的事件通知机制