Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use "ngProjectAs" attribute?

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>
like image 239
Rafi Henig Avatar asked Oct 26 '19 20:10

Rafi Henig


People also ask

Why do we use NG-content in Angular?

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.

What is the difference between Ng-content ng container and ng-template?

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.

What does ng-content do?

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.


1 Answers

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.

like image 109
Andrei Gătej Avatar answered Nov 13 '22 01:11

Andrei Gătej