TL;DR:
Explanation:
I\'m dynamically creating
After looking around for similar answers, it dawned on me that the default solution is actually very standard: extract a component, where you can hardcode your template variable, and generate as many instances of this component as you need with the *ngFor
directive.
I understand there may be concerns about performance, and I don't know enough about that to comment either way (who knows, it may end up being faster), but IMO it should definitely be the first solution to be envisioned.
And the DynamicComponentLoader
mentionned in Eric Martinez answer seems to be gone from Angular 5 anyway (couldn't find it in the docs).
The problem with that approach is you can't dynamically generate variable names.
Another possible approach is using loadAsRoot which instead of using a variable name, uses an id
which can contain a dynamic name.
// This will generate dynamically the id value
template: `
<div *ng-for="#idx of data">
<div id="dynamicid_{{idx}}">Dynamic</div>
</div>`
Then you set the list you want to iterate over
this.data = [1,2,3,4,5,6];
for(var i = 0; i < this.data.length; i++) {
// Third argument is the injector that I'm not using, so I just nulled it
dynamicComponentLoader.loadAsRoot(DynamicComponent, '#dynamicid_'+this.data[i], null);
}
Here's the plnkr with an example working.
I hope it helps.