Angular - Single Slot Content Projection



A component involving only one content projection is called single-slot content projection.

Example - Single 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> tag in the template, i.e. content-projection-sample.html file 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> 

Step 4: Use the content-projection-sample component in the app.html file as shown below −

app.html

<app-content-projection-sample>
   <p>This is external content</p>
</app-content-projection-sample>
<router-outlet></router-outlet>

Step 5: Now import the ContentProjectionSampleComponent inside the App Component.

App.ts

import { Component, signal } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ContentProjectionSample } from './content-projection-sample/content-projection-sample';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet, ContentProjectionSample],
  templateUrl: './app.html',
  styleUrl: './app.css'
})
export class App {
  protected readonly title = signal('nestedApplication');
}

Output

The output of the application is as shown below −

Application Output
Advertisements