Problem Description
I defined a Component that allows consumer Component to project its custom content via content projection
:
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 {}
It contains two areas, default
and question
.
For the question area, the content can be projected into app-zippy-basic
only when the content provided by the Component is consumed and the selector specified in line 10 is satisfied.
My consumption code is as follows:
<app-zippy-basic>
<p #question>
带了问号的 p 节点
</p>
<p>普通 p 节点</p>
</app-zippy-basic>
My expected result:
- Ordinary p node, which appears in the default area;
- The p node with a question mark appears in the question area.
Actual test result: The question area is empty.
problem analysis
According to the definition of Angular's official website, the syntactic meaning of select="[question]" is to project the dom node of attribute
with question
in the consuming Component to app-zippy-basic
. Therefore, the #
in line 23 should be removed to produce a p-node with the attribute question
:
After removing it, the p node is displayed in the default
area as we expected:
Let's find out how the p node with the question
attribute is selected and projected by single-step debugging.
The Angular framework internally maintains a data structure called LView
or Logic View
, which is an array:
Contents of LView
:
The array element with index 21, rawSlotValue
, stores the p node with the question attribute that needs to be projected into the question area.
Summarize
If a component contains a ng-content
element without a select attribute, the instance receives all projected components that do not match any other ng-content
element.
Logical View (LView) Represents an instance of a template (TView). We use the word logic to emphasize how developers view applications from a logic perspective. ParentComponent contains a ChildComponent. From a logical point of view, we think that ParentComponent contains ChildComponent, hence the
logic. The word logic contrasts with the final concept of render trees.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。