0 day streak
javascript / expert
Snippet

Headless UI Pattern with TemplateRef for Decoupled Rendering

The Headless UI pattern decouples business logic and state management from the visual representation. By using @ContentChild to capture a TemplateRef, the component handles the iteration and context provision while letting the consumer define the exact HTML structure and styling.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Component({
selector: 'app-data-list',
standalone: true,
template: `
@for (item of items(); track item.id) {
<ng-container
[ngTemplateOutlet]="itemTemplate"
[ngTemplateOutletContext]="{ $implicit: item }">
</ng-container>
}
`})
export class DataListComponent<T extends { id: any }> {
items = input.required<T[]>();
@ContentChild(TemplateRef) itemTemplate!: TemplateRef<{ $implicit: T }>;
}
angular
Breakdown
1
items = input.required<T[]>();
Uses the new Signal-based input API for reactive data handling.
2
@ContentChild(TemplateRef) itemTemplate!;
Captures the user-provided template from the component's content projection.
3
[ngTemplateOutletContext]="{ $implicit: item }"
Passes the data item to the template using the implicit context variable.