Binding events when using a ngForTemplate in Angular 2

Been looking for an answer to this for a week now and I finally came up with a pretty decent solution. Instead of using ngForTemplate I would suggest using ngTemplateOutlet.

It is already described pretty well here:
angular2 feeding data back to `<template>` from `[ngTemplateOutlet]`

The custom template for the list items is placed between the component tags:

<my-list>
  <template let-item="item">
    Template for: <b>{{item.text}}</b> ({{item.id}})
  </template>
</my-list>

And the component template:

<ul>
  <li *ngFor="let item of listItems" (click)="pressed(item)">
    <template 
      [ngTemplateOutlet]="template" 
      [ngOutletContext]="{
        item: item
      }">
    </template>
  </li>
</ul>

I made an example here: https://plnkr.co/edit/4cf5BlVoqzZdUQASVQaC?p=preview

Leave a Comment