Search code examples
angularangular5ng-templateng-container

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.


Solution

  • 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>