Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an ng-content be used inside of an ngFor?

Tags:

angular

We'd like to put a ng-content inside of an *ngFor and then specify the contents of the ng-content when the component containing the ngFor is used. Is it possible?

<li *ngFor="let data of dataSource">
  <ng-content></ng-content>
</li>

Demo

like image 836
Eric H Avatar asked Feb 04 '16 00:02

Eric H


People also ask

Can we use ngFor with Ng-container?

ng-Container with ngForWithout ng-container , the only way to achieve this is by using the span element as shown. This adds the unnecessary DOM element.

Can I use ngIf inside ngFor?

While you are not allowed to use *ngIf and *ngFor in the same div (it will gives an error in the runtime) you can nest the *ngIf in the *ngFor to get the desired behavior.

What is use of NG-content in Angular 4?

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 and ng-template?

To sum up, ng-content is used to display children in a template, ng-container is used as a non-rendered container to avoid having to add a span or a div, and ng-template allows you to group some content that is not rendered directly but can be used in other places of your template or you code.


2 Answers

Yes, it will not give you proper result. But this can be achieved by ng-template and TemplateRef.

I have made a demo. You can see the demo that may help.

child.component.html

<li *ngFor="let rowDetail of dataSource">
  <ng-container
     *ngIf="headerTemplateRef"
     [ngTemplateOutlet]="headerTemplateRef"
     [ngTemplateOutletContext]="{$implicit:rowDetail}"
  >
  </ng-container>
</li>

child.component.ts

@ContentChild('header',{static: false}) headerTemplateRef: TemplateRef<any>;

parent.component.html

<child-app [data]="data"> 
    <ng-template let-rowDetail #header>
        <div style="padding-left:35px;">
            <div>{{rowDetail.name}}</div>
        </div>
    </ng-template>
</child-app>
like image 51
Tushar Ghosh Avatar answered Oct 29 '22 01:10

Tushar Ghosh


It is possible but probably doesn't produce the desired result. Children passed by the parent can only projected once (no matter how many <ng-content> are there. If the <ng-content> elements don't select specific and different parts of the passed children using the select attribute, then everything is projected to the first <ng-content> with the default selector (none).

To make this work you probably want a custom ngFor that repeats the content passed to <ng-content>.

NgFors ngForTemplate might help in your use case.

See also Angular2 child component as data

like image 22
Günter Zöchbauer Avatar answered Oct 29 '22 02:10

Günter Zöchbauer