Content projection in Angular allows you to create flexible and customizable components
November 6, 2024 11:18 PM
Content projection in Angular allows you to create flexible and customizable components by allowing the parent component to project content into the child component. This is similar to using {children}
props in React.
Enhancing the course.component.html with Content Projection
Let's enhance the course.component.html to use content projection. We'll use Angular's <ng-content>
directive to allow the parent component to project content into specific parts of the CourseComponent
.
Updated course.component.html
<div class="course" [id]="index" [ngClass]="{'class-name': true}" [style.text-decoration]="'none'" [ngStyle]="cardStyles()">
<h1>{{ course.id }} {{ course.description }}</h1>
<div style="min-width: 359px; min-height: 202px;">
<img #courseImageRef [src]="course.iconUrl" [alt]="course.description">
</div>
<p>{{ course.longDescription }}</p>
<div class="course-category">
@switch (course.category) {
@case ("BEGINNER") {
<span [ngClass]="cardClasses()"> ?♂️ Beginner </span>
}
@case ("INTERMEDIATE") {
<span [ngClass]="cardClasses()"> ????? Intermediate </span>
}
@case ("ADVANCED") {
<span [ngClass]="cardClasses()"> ???? Advanced</span>
}
@default {
<span [ngClass]="cardClasses()"> ? Unknown</span>
}
}
</div>
<!-- Content projection slots -->
<ng-content select="[course-extra-info]"></ng-content>
<ng-content select="[course-actions]"></ng-content>
</div>
- Content Projection Slots:
<ng-content select="[course-extra-info]"></ng-content>
: This slot allows the parent component to project additional information about the course.<ng-content select="[course-actions]"></ng-content>
: This slot allows the parent component to project action buttons or links related to the course.
Usage in Parent Component
Here's how you can use the enhanced CourseComponent
in a parent component, projecting custom content into the defined slots.
Parent Component Template
<app-course [course]="course" [index]="index" [ngClass]="{'class-name': true}" [ngStyle]="cardStyles()">
<div course-extra-info>
<p>Additional information about the course can go here.</p>
</div>
<div course-actions>
<button(click)="enroll(course.id)">Enroll Now</button>
<button(click)="share(course.id)">Share</button>
</div>
</app-course>
- Custom Content Projection:
<div course-extra-info>
: This div will be projected into the<ng-content select="[course-extra-info]"></ng-content>
slot in theCourseComponent
.<div course-actions>
: This div will be projected into the<ng-content select="[course-actions]"></ng-content>
slot in theCourseComponent
.
By using content projection, you can make your CourseComponent
more flexible and customizable. The parent component can project custom content into the child component, similar to how {children}
props work in React. This approach allows you to create configurable components that can be easily customized by the component user.
Comments