The code involved in this article is located in this Github repository: https://github.com/wangzixi-diablo/ngDynamic
Problem Description
I use the following code for parameter passing of ng-template template:
<ng-template #inputTemplateWithContent let-param let-name="name">
<div>参数1: {{param}}</div>
<div>参数2: {{name}}</div>
</ng-template>
Here, for the code position 2 in the above figure, I use the keyword let-
to define a local variable name
that can only be accessed in the name
.
And for the param at code position 1, I didn't specify the attribute name mapped to the context object, so I expected it to use the default attribute of the same name in the context object, so the last div element should display the value of the attribute
param
: default value.
However, the actual execution result is that the displayed value of the first div element is empty:
problem analysis
The root of this problem is how to pass a property in the context object to the template as the default property of .
Found this documentation on default values in Angular official website :
The exact meaning of the context object:
The context object attached to the EmbeddedViewRef. This should be a JSON object whose keys will be available for bindings declared by the local template let. Using the key $implicit in the context object will set its value to the default.
The documentation mentions that the default properties should be identified with $implicit
.
We searched according to the keyword $implicit
in the source code, and found the constant IMPLICIT_REFERENCE
, and then searched according to the constant to find the place where the Angular framework source code parses $implicit
:
Here we can find the logic of Angular parsing template variable:
Start and end symbols for InterpolationConfig
: {{
, }}
solution
Modify param
at the position of legend 1 in the following figure to $implicit
:
Summarize
From the following call stack, you can also observe the HTML elements contained in the template and the corresponding DOM nodes in memory:
ng-template, ng-container and br correspond to the following three elements in the HTML file:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。