i am trying to create template reference through ngFor loop. but not works.
ts file:
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
members = [
{
name: 'name1',
id:"one"
},
{
name: 'name2',
id:"two"
},
{
name: 'name3',
id:"three"
}
]
}
template:
<div class="container">
<h2>Test popover</h2>
<p>
How to declare a dynamic template reference variable inside a ngFor element?
</p>
</div>
<div *ngFor="let member of members">
<ng-container [ngTemplateOutlet]="{{member.id}}"
>Hello, <b>{{ member.name }}</b
>!</ng-container
>
</div>
<ng-template #one> one </ng-template>
<ng-template #two> two </ng-template>
<ng-template #three> three </ng-template>
I am getting an error as:
Type '{ "": any; }' is not assignable to type 'TemplateRef<any>'. Object literal may only specify known properties, and '""' does not exist in type 'TemplateRef<any>'.
Update:
If you want to pass
ngTemplateto child, you can usecontentChildforked stackblitz
Solution1:
Instead of hardcoding the template names, you can just render based on the index
forked stackblitz
Solution2:
You can chain ternary conditions so that you get the output as required
forked stackblitz