What is a template context?
In Angular, the template context is an object that holds the data and variables available inside ng-template during its rendering. Through the context, the template receives values for local variables (let-) and $implicit.
Main points
- Passing data into the template:
html
<ng-template #tpl let-user>
<p>{{ user.name }}</p>
</ng-template>
<ng-container *ngTemplateOutlet="tpl; context: { $implicit: currentUser }"></ng-container>contextis the object that passes the data.$implicitlets the template use a default value without an explicit variable name.
- Local variables through
let-:
- Variables can be declared in the template:
html
<ng-template let-item="product">
<p>{{ item.name }}</p>
</ng-template>iteminside the template takes its value from theproductproperty of the context object.
- Reusability:
- The context makes the template reusable, allowing different data to be substituted on each render.
In other words, the template context is a "data environment" that Angular supplies to the template for local variables to work and for dynamic display.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.