0
0
Angularframework~30 mins

ng-content for slot-based composition in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Using <code>ng-content</code> for Slot-Based Composition in Angular
📖 Scenario: You are building a reusable Angular card component that can display different content in specific areas like header, body, and footer. This helps you reuse the card layout but show different content inside it.
🎯 Goal: Create an Angular component called app-card that uses ng-content with named slots to allow inserting custom header, body, and footer content from the parent component.
📋 What You'll Learn
Create an Angular component app-card with a template using ng-content and named slots
Use select attributes on ng-content to define slots for header, body, and footer
In the parent component template, use app-card and provide content for each slot using elements with matching selectors
Ensure the card layout uses semantic HTML and is accessible
💡 Why This Matters
🌍 Real World
Slot-based composition with <code>ng-content</code> is common in Angular to build flexible, reusable UI components like cards, modals, and tabs that accept custom content from their parents.
💼 Career
Understanding <code>ng-content</code> and slot-based content projection is essential for Angular developers to create maintainable and reusable component libraries in professional projects.
Progress0 / 4 steps
1
Create the app-card component template with basic structure
Create the app-card.component.html file with a section element containing three div elements with classes card-header, card-body, and card-footer. Inside each div, add an ng-content tag without any select attribute.
Angular
Need a hint?

Use <ng-content> inside each div to mark where content will be inserted.

2
Add named slots to ng-content using select attributes
Modify the app-card.component.html so that the ng-content inside card-header has select="[card-header]", inside card-body has select="[card-body]", and inside card-footer has select="[card-footer]".
Angular
Need a hint?

Use the select attribute on ng-content to define named slots matching attribute selectors.

3
Use app-card in parent template with slot content
In the parent component template, add an <app-card> element. Inside it, add three elements: a header with attribute card-header containing the text My Card Title, a p with attribute card-body containing This is the card body content., and a footer with attribute card-footer containing Footer info here..
Angular
Need a hint?

Use elements with attributes matching the select values in app-card to fill slots.

4
Add basic CSS for card layout and accessibility
Add CSS styles to the app-card.component.css file to give the card a border, some padding, and spacing between header, body, and footer. Use semantic HTML roles if needed for accessibility.
Angular
Need a hint?

Add CSS rules for the card container and its parts to improve visual layout and clarity.