A context object supplies values to bindings inside an instantiated Angular template. Its properties are mapped to template variables, allowing reusable content to be tailored each time it is inserted. section 12.2.4
Use the context object in two complementary ways:
- Bind an object to ngTemplateOutletContext. A template declares variables with let- attributes, whose expressions select matching context properties. section 12.2.4
- Provide $implicit when a structural directive supplies the primary item value. A declaration such as let-item receives that value without naming $implicit. section 15.3
- Add named properties for supplemental state such as index, odd, even, first, and last, then expose them through additional let- variables. section 15.3.1
Passing different values to one template
Declare a reusable template with `let-text="title"` and bind `{title: 'Header'}` or `{title: 'Footer'}` through `ngTemplateOutletContext`. The same template then renders different headings. A custom iterator follows the same pattern: `createEmbeddedView` receives a context containing the current product as `$implicit`, while additional properties can drive striped row classes and display positions. section 12.2.4 section 15.3 section 15.3.1
Listing 12.15. Providing context data in the template.html file in the src/app folder
<ng-template #titleTemplate let-text="title">
<h4 class="p-2 bg-success text-white">{{text}}</h4>
</ng-template>
<ng-template [ngTemplateOutlet]="titleTemplate"
[ngTemplateOutletContext]="{title: 'Header'}">
</ng-template>
<div class="bg-info p-2 m-2 text-white">
There are {{count()}} products.
</div>
<ng-template [ngTemplateOutlet]="titleTemplate"
[ngTemplateOutletContext]="{title: 'Footer'}">
</ng-template>
Inspect a complete ngTemplateOutlet example that passes Header and Footer values through a context object. section 12.2.4
Listing 15.9. The contents of the iterator.directive.ts file in the src/app folder
import { Directive, ViewContainerRef, TemplateRef, Input}
from "@angular/core";
@Directive({
selector: "[paForOf]"
})
export class PaIteratorDirective {
constructor(private container: ViewContainerRef,
private template: TemplateRef<Object>) { }
@Input("paForOf")
dataSource: any;
ngOnInit() {
this.container.clear();
for (let i = 0; i < this.dataSource.length; i++) {
this.container.createEmbeddedView(this.template,
new PaIteratorContext(this.dataSource[i]));
}
}
}
class PaIteratorContext {
constructor(public $implicit: any) { }
}
Inspect the custom iterator implementation that creates one embedded view per product and supplies its implicit value. section 15.3

