Angular Reusable HTML with NgTemplateOutlet

When we speak reusability in Angular, the component is the final solution. But what if we're only reusing some HTML snipplet, it might be heavy and hard to maintain to create a separate component. One another solution is to use tngTemplateOutlet.

Here are some usage of ngTemplateOutlet

<ng-template #myListTemplate let-list="list">
    <div *ngFor="let item of list">
        <ng-container [ngTemplateOutlet]="myItemTemplate"
            [ngTemplateOutletContext="{ $implicit: item}">
        </ng-container>
    </div>
</ng-template>

<ng-template #myItemTemplate let-item>
  <span>{{ item.name }}</span>
    <p>{{ item.description }}</p>
    <button (click)="onClick(item)">Show more</button>
</ng-template>

we can use above template with ngTemplateOutlet directive on ng-container:

<ng-container [ngTemplateOutlet]="myListTemplate" 
    [ngTemplateOutletContext="{list: taskList}">
</ng-container>

context object on ngTemplateOutlet should be an object, the object key can be bind in template let declarations. 2 ways to make task variable available as item in the template.

1.let-item and [ngTemplateOutletContext="{ $implicit: item}"
$implict will set the value as default.
2.let-item='task'and context object contains task key: [ngTemplateOutletContext]="{task: task}"

we can still pass the structural data to ngTemplateOutlet directive like:

<ng-container *ngTemplateOutlet="myItemTemplate; context: { $implicit: item }"></ng-container>