angular content projection with two ng containers sample code
- User
angular content projection with two ng containers sample code
- Assistant
Below is a minimal, self-contained example that shows how to do multi-slot (a.k.a. multiple-content projection) using two
ng-containerelements.
Becauseng-containeris a structural, “no-DOM” wrapper, it lets us group and label the projection slots without adding extra elements to the final markup.🏗️ 1. Child component –
fancy-card.component.ts/html// fancy-card.component.ts import { Component } from '@angular/core'; @Component({ selector: 'fancy-card', templateUrl: './fancy-card.component.html', styleUrls: ['./fancy-card.component.css'] // (optional) }) export class FancyCardComponent {}<!-- fancy-card.component.html --> <div class="card"> <!-- HEADER SLOT --> <ng-container class="card-header"> <!-- Everything coming from the parent that carries the attribute card-header will be projected here. --> <ng-content select="[card-header]"></ng-content> </ng-container> <!-- BODY SLOT --> <ng-container class="card-body"> <!-- Everything coming from the parent that carries the attribute card-body will be projected here. --> <ng-content select="[card-body]"></ng-content> </ng-container> </div>Key points
• Twong-contenttags → two independent “slots”.
• Each is wrapped by anng-containerso there is no extra tag in the rendered HTML.
• We use attribute selectors ([card-header],[card-body]) to tell Angular which bit of the parent’s markup goes where.
🎨 2. How to consume the component –
app.component.html<fancy-card> <!-- Anything with card-header attr lands in the first ng-container --> <h2 card-header>Project Star ✨</h2> <!-- Anything with card-body attr lands in the second ng-container --> <p card-body> This project aims to demonstrate Angular content projection with two distinct slots using <code>ng-container</code>. </p> </fancy-card>Rendered DOM (simplified)
<div class="card"> <h2 class="card-header">Project Star ✨</h2> <p class="card-body">This project aims to demonstrate…</p> </div>Notice:
ng-containerwrappers disappear; only the projected elements (h2,p) remain.
🧩 3. Optional CSS –
fancy-card.component.css.card { border: 1px solid #0077ff; border-radius: 6px; padding: 12px; } .card-header { font-weight: 700; margin-bottom: 8px; } .card-body { font-size: 14px; color: #333; }
That’s it!
You now have a reusableFancyCardComponentthat cleanly projects two distinct parts of its content—header and body—using twong-containerelements without cluttering the DOM. Happy coding! 🎉
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.