0
0
AngularHow-ToBeginner · 3 min read

How to Use ngProjectAs in Angular: Simple Guide

In Angular, ngProjectAs lets you change how projected content matches selectors in <ng-content>. Use ngProjectAs on an element inside a component to make Angular treat it as if it had a different CSS selector during content projection.
📐

Syntax

The ngProjectAs directive is used as an attribute on an element inside a component's content. It takes a CSS selector string as its value. Angular uses this selector to match the element against <ng-content> selectors in the component template.

  • <element ngProjectAs="selector">: The element will be projected as if it matches selector.
  • selector: A CSS selector string like div, .class, or [attr].
html
<!-- Syntax example -->
<element ngProjectAs=".some-class">Content</element>
💻

Example

This example shows a parent component projecting content into different slots using selectors. The child element uses ngProjectAs to appear as if it matches a different selector, so it projects into the intended slot.

html
<!-- child.component.html -->
<div>
  <ng-content select=".header"></ng-content>
  <ng-content select=".body"></ng-content>
</div>

<!-- parent.component.html -->
<child-component>
  <p ngProjectAs=".header">This is projected as header</p>
  <p class="body">This is projected as body</p>
</child-component>
Output
<div> <p>This is projected as header</p> <p class="body">This is projected as body</p> </div>
⚠️

Common Pitfalls

  • Not using ngProjectAs when the element's actual selector does not match any <ng-content> selector causes the content to not project.
  • Using an incorrect or overly broad selector in ngProjectAs can cause content to project into the wrong slot.
  • Remember ngProjectAs only affects projection matching, not styling or behavior.
html
<!-- Wrong: no ngProjectAs, content won't project -->
<child-component>
  <p>This won't project because no matching selector</p>
</child-component>

<!-- Right: use ngProjectAs to match selector -->
<child-component>
  <p ngProjectAs=".header">This projects correctly</p>
</child-component>
📊

Quick Reference

ngProjectAs Cheat Sheet:

  • ngProjectAs=".class": Project as element with class.
  • ngProjectAs="tag": Project as element with tag name.
  • ngProjectAs="[attr]": Project as element with attribute.
  • Use to fix projection when element's real selector doesn't match <ng-content>.

Key Takeaways

ngProjectAs changes how Angular matches projected content selectors.
Use ngProjectAs to make an element appear as a different selector for projection.
It only affects content projection, not styling or behavior.
Incorrect or missing ngProjectAs can cause content not to project.
Always match ngProjectAs value to the <ng-content> selector you want.