Angular - Conditional Content Projection
Conditional content projection is projecting a content when certain condition is met. We can use ng-content to conditionally project the content. But it is not recommended since <ng-content> will be initialized even if the content is not going to be rendered. Instead, we can use <ng-template> to project the content safely since it will initialize the content only when it is going to be rendered.
Example - Conditional 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: In the component's template, use @if for checking the condition, ng-container and ng-template to display the template (greet.template) in the components template as shown below −
ContentProjectionSample.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>
@if (show) {
<ng-container *ngTemplateOutlet="greet"></ng-container>
}
<ng-template #greet>Hi, I am coming from conditional template</ng-template>
Output
Step 4: Run the application and check the output to find whether content is rendered through conditional projection concept or not:
Step 5: Update the condition, show in the component to false and check the output to find that the ng-template content is not rendered.
export class ContentProjectionSampleComponent {
show = false;
@ContentChild(GreetContentDirective) greet!: GreetContentDirective;
}