DEV Community

Andrei Gatej
Andrei Gatej

Posted on

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

Discussion (0)