angular content projection with two ng containers sample code
- User
angular content projection with two ng containers sample code
- Assistant
Here's a concise example of Angular content projection using two
ng-containerelements to dynamically project distinct content regions viangTemplateOutlet.
🧱 ParentComponent
This component accepts two templates (
headerTemplateandbodyTemplate) and usesng-containerwith*ngTemplateOutletto project them independently.import { Component, Input } from '@angular/core'; @Component({ selector: 'app-parent', template: ` <div class="card"> <!-- Header section --> <div class="card-header"> <ng-container *ngTemplateOutlet="headerTemplate"></ng-container> </div> <!-- Body section --> <div class="card-body"> <ng-container *ngTemplateOutlet="bodyTemplate"></ng-container> </div> </div> `, styles: [ ` .card { border: 1px solid #ccc; padding: 1rem; max-width: 400px; margin: 1rem auto; } .card-header { font-weight: bold; background-color: #f8f8f8; padding: 0.5rem; border-bottom: 1px solid #ddd; } .card-body { padding: 1rem 0; } ` ] }) export class ParentComponent { @Input() headerTemplate!: any; @Input() bodyTemplate!: any; }
📄 App Usage (Consumer Component)
In the consumer component's template, define two
<ng-template>blocks and pass them to theParentComponent.<ng-template #header> <h2>Custom Header</h2> </ng-template> <ng-template #body> <p>This is the main content area.</p> </ng-template> <app-parent [headerTemplate]="header" [bodyTemplate]="body"></app-parent>
🧩 Optional: Passing Context to Templates
If you want to pass data to the templates (e.g., dynamic values), you can extend the example:
Updated ParentComponent
@Input() headerContext: any = {}; @Input() bodyContext: any = {};Update the
ngTemplateOutletusage:<ng-container *ngTemplateOutlet="headerTemplate; context: headerContext"></ng-container> <ng-container *ngTemplateOutlet="bodyTemplate; context: bodyContext"></ng-container>Usage with Context
<ng-template #header let-title="title"> <h2>{{ title }}</h2> </ng-template> <ng-template #body let-message="message"> <p>{{ message }}</p> </ng-template> <app-parent [headerTemplate]="header" [headerContext]="{ title: 'Welcome!' }" [bodyTemplate]="body" [bodyContext]="{ message: 'This is dynamic content.' }" ></app-parent>
✅ Summary
ng-containeris used as a lightweight placeholder for content.*ngTemplateOutletdynamically renders a givenTemplateRef.- This pattern is ideal for reusable UI components like cards, modals, or layout wrappers that require customizable regions.
This approach gives you fine-grained control over content projection using Angular's powerful template system.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.