AngularM
AngularM

Reputation: 16628

Angular - issue looping with an ng-container

I want to call an ng-template from within a ngFor using an ng-container

My list is an array and has a list of objects. one property of an object is title - seen in the ng-template.

Html:

<ul>

    <li *ngFor='let item of list;let i = index'>

        <ng-container *ngTemplateOutlet="itemTemplate;context:item"></ng-container>

    </li>

</ul>

<ng-template #itemTemplate let-item="item">
    <p>{{ item?.title }}</p>
</ng-template>

Note: Issue is the let-item seems to be undefined or an empty object. which is strange since im passing it in.

Upvotes: 2

Views: 9893

Answers (3)

Vignesh
Vignesh

Reputation: 1212

<ul>
  <li *ngFor="let i of list">
    <ng-container *ngTemplateOutlet="itemTemplate; context: { i: i }">
    </ng-container>
  </li>
</ul>
<ng-template #itemTemplate let-item="i">
    <p>{{ i?.title }}</p>
</ng-template>

Upvotes: 0

cyr_x
cyr_x

Reputation: 14257

Your use of the templateOutletContext is slightly wrong.

You could use the $implicit key for the context and then bind it to you template like this:

<ul>
  <li *ngFor="let item of list">
    <ng-container *ngTemplateOutlet="itemTemplate; context: { $implicit: item }">
    </ng-container>
  </li>
</ul>
<ng-template #itemTemplate let-item>
    <p>{{ item?.title }}</p>
</ng-template>

or with a named key:

<ul>
  <li *ngFor="let item of list">
    <ng-container *ngTemplateOutlet="itemTemplate; context: { item: item }">
    </ng-container>
  </li>
</ul>
<ng-template #itemTemplate let-item="item">
    <p>{{ item?.title }}</p>
</ng-template>

Upvotes: 5

gaurav bankoti
gaurav bankoti

Reputation: 224

First of all you element has to be inside scope of *ngFor. like if you want to repeat a

tag inside tag. then the code would be

<div *ngFor="item in items">
  <p>{{item}}</p>
</div>

Similarly in your case has to be inside

  • tag

    <ul>
    
        <li *ngFor='let item of list;let i = index'>
    
            <ng-container *ngTemplateOutlet="itemTemplate;context:item"></ng-container>
    <ng-template #itemTemplate let-item="item">
        <p>{{ item?.title }}</p>
    </ng-template>
    
        </li>
    
    </ul>
    

    Upvotes: 0

  • Related Questions