DEV Community

Andrei Gatej
Andrei Gatej

Posted on

18 5

Angular: A use case for `ngProjectAs`

I have a List component that's used to render a list. (Well, I don't, but I've tried to distil my problem down into a noddy example that's easy to understand).

The template for the List component has one or more ListItem components that allow the list items to be defined…

I found ngProjectAs to be useful when I wanted to project an ng-container with a certain selector.

@Component({
 selector: 'awesome-comp',
 template: `
  <ng-content select="[foo]"></ng-content>
 `
})
export class AwesomeComponent { }
Enter fullscreen mode Exit fullscreen mode
<!-- another-awesome.component.html -->

<!-- We can avoid a redundant `div` like this one -->
<awesome-comp>
 <div foo>
  <h1> <!-- ... --> </h1>
   <p> <!-- ... --> </p>
 </div> 
</awesome-comp>

<!-- By using `ngProjectAs` -->
<awesome-comp>
 <ng-container ngProjectAs='[foo]'>
  <h1> <!-- ... --> </h1>
   <p> <!-- ... --> </p>
 </ng-container> 
</awesome-comp>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay