Skip to main content

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

  1. 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>
  • context is the object that passes the data.
  • $implicit lets the template use a default value without an explicit variable name.
  1. Local variables through let-:
  • Variables can be declared in the template:
html
<ng-template let-item="product"> <p>{{ item.name }}</p> </ng-template>
  • item inside the template takes its value from the product property of the context object.
  1. 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.