How does the $implicit variable work in a template context?
In Angular, $implicit is a special template context variable used to pass an "implicit" value into ng-template or a structural directive, when you do not want to explicitly name the variable.
Main points
- Use with
ng-template:
html
<ng-template #tpl let-user>
<p>{{ user.name }}</p>
</ng-template>- Here
let-usergets its value from the context. - If the context is passed via
$implicit, the variable name can be omitted:
ts
<ng-container *ngTemplateOutlet="tpl; context: { $implicit: currentUser }"></ng-container>- In the template,
let-userwill automatically get the value ofcurrentUser.
- Application:
$implicitis convenient when a template expects one main value, so you do not need to create an explicit name.- Allows writing a template generically, without tying it to a specific property name.
- Example with a directive:
html
<ng-template let-item>
<p>{{ item }}</p>
</ng-template>
<ng-container *ngFor="let i of items; let t = tpl">
<ng-container *ngTemplateOutlet="tpl; context: { $implicit: i }"></ng-container>
</ng-container>iautomatically becomes$implicitin the template, accessible throughlet-item.
In other words, $implicit is an "implicit" variable for passing the main value into a template, which lets templates be more generic and convenient.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.