I've come across the following code where ngProjectAs
attribute is being used within ng-container
. what is it used for, what problem does it address?
<mat-form-field [formGroup]="group">
<input matInput [formControlName]="field.name">
<ng-container *ngFor="let validation of field.validations;" ngProjectAs="mat-error">
<mat-error *ngIf="group.get(field.name).hasError(validation.name)">{{validation.message}}</mat-error>
</ng-container>
</mat-form-field>
The ng-content is used when we want to insert the content dynamically inside the component that helps to increase component reusability. Using ng-content we can pass content inside the component selector and when angular parses that content that appears at the place of ng-content.
ng-container serves as a container for elements which can also accept structural directives but is not rendered to the DOM, while ng-template allows you to create template content that is not rendered until you specifically (conditionally or directly) add it to the DOM.
The ng-content tag is used for content projection. It is basically a placeholder to hold the dynamic content until it is parsed. Once the template is parsed, Angular replaces the tag with content.
I find ngProjectAs
useful when I want to project an ng-container
under a certain selector.
Here you can find a short article about it.
Imagine you have this this component:
@Component({
selector: 'awesome-comp',
template: `
<ng-content select="[foo]"></ng-content>
`
})
export class AwesomeComponent { }
As you know, this is how you'd project content inside awesome-component
:
<awesome-comp>
<p>Hello there!</p>
</awesome-comp>
But what happens when you want to project more elements/components under the same selector?
One way(not really recommended) would be to do this:
<awesome-comp>
<div foo>
<h1> <!-- ... --> </h1>
<p> <!-- ... --> </p>
</div>
</awesome-comp>
As you can see, we're adding a redundant div in order to be able to project multiple elements.
Now, here is how ngProjectAs
saves the day:
<awesome-comp>
<ng-container ngProjectAs='[foo]'>
<h1> <!-- ... --> </h1>
<p> <!-- ... --> </p>
</ng-container>
</awesome-comp>
The above snippet won't add any redundant wrapper elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With