Issue
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>
Solution
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 { }
consumer.component.html
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.
Answered By - Andrei Gătej
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.