angularantdng-template

passing context to ng-template when used by its local reference


I have a component that looks like this:

<nz-collapse>
  <nz-collapse-panel *ngFor="let item of items" [nzHeader]="collapseHeader">
    <div class="item">
      <!-- some content here -->
    </div>
  </nz-collapse-panel>
</nz-collapse>

<ng-template #collapseHeader let-item>
  <nz-divider [nzText]="item.name"></nz-divider>
</ng-template>

How can i pass each item as context to my ng-template? the library doesn't offer a way to do it. (nzHeader only exepts strings and TemplateRef as arguments, no other type of views)


Solution

  • One way to solve the issue is to completely bypass the need for giving context to a template. Instead, let's give an Input() to a component, because this is easy.

    Let's create a CollapseWrapperComponent with app-collapse-wrapper-component as its selector. Here's the ts and the html:

    export class CollapseWrapperComponent {
      @Input() public item: Item;
    }
    
    <nz-collapse-panel [nzHeader]="collapseHeader">
      <ng-content></ng-content>
    </nz-collapse-panel>
    
    <ng-template #collapseHeader>
      <nz-divider [nzText]="item.name"></nz-divider>
    </ng-template>
    

    And then in the parent component's html, we can now iterate over this component in our *ngFor:

    <nz-collapse>
      <app-collapse-wrapper *ngFor="let item of items">
        <div class="item">
          <!-- some content here -->
        </div>
      </app-collapse-wrapper>
    </nz-collapse>
    

    Now we basically have one <ng-template> for each item, so no need for context.