Angular - Multi-Slot Content Projection



Angular allows multiple content to be projected in the component as well and it is called multi-slot content projection.

Example - Multi-slot Content Projection

Let us understand the content projection by creating the above explained component.

Step 1: Create a projectionSample application using the below command −

ng new projectionSample

Step 2: Navigate to project folder and create a new component with the name content-projection-sample:

cd projectSample

ng generate component content-projection-sample
CREATE src/app/content-projection-sample/content-projection-sample.spec.ts (675 bytes)
CREATE src/app/content-projection-sample/content-projection-sample.ts (271 bytes)
CREATE src/app/content-projection-sample/content-projection-sample.css (0 bytes)
CREATE src/app/content-projection-sample/content-projection-sample.html (41 bytes)

Step 3: Add <ng-content> along with selector attribute in the component template, content-projection-sample.html as shown below −

content-projection-sample.html

<p>This is content from the component template</p>
<ng-content></ng-content>
<p>This is another content from component template</p>
<ng-content select="[second]"></ng-content>

Step 4: Update the app component template, app.html as shown below −

app.html

<app-content-projection-sample>
   <p>This is external content</p>
   <p second>This is yet another external content</p>
</app-content-projection-sample>

<router-outlet></router-outlet>

Here, the value of selector attribute (second) set in the component template is used in the content to be projected.

Output

Step 3: Now, run the application and check the output.

multi-slot content
Advertisements