4

I have json object which holds some html strings. Need to create multiple ng-template with unique reference variable.

   <div *ngFor="let el of ElementList">
    <ng-template #el.id>
      <div [innerHtml]="el.html"></div>
    </ng-template> 
   </div>

Here is my ElementList array

 ElementList = [
    {id: 'h1', html: '<h1>sample heading</h1>'},
    {id: 'h2', html: '<h2>sample heading</h2>'},
    {id: 'h3', html: '<h3>sample heading</h3>'},
  ];

Can anyone help me on this

NIDHIN VINCENT
  • 225
  • 1
  • 2
  • 9
  • 2
    `....` – dcg Jun 21 '19 at 15:48
  • Why do you want to have unique template reference variable names? How will you use these variables? – ConnorsFan Jun 21 '19 at 15:48
  • 1
    Just change your `ng-template` as in @Hamza Neffati answer – dcg Jun 21 '19 at 15:51
  • 1
    Possible duplicate of [Dynamic template reference variable inside ngFor (Angular 2)](https://stackoverflow.com/questions/44440879/dynamic-template-reference-variable-inside-ngfor-angular-2) – Douglas P. Jun 21 '19 at 15:53
  • @dcg - How is that supposed to work? What HTML element will have the `id`? – ConnorsFan Jun 21 '19 at 15:53
  • @ConnorsFan Do you suggest the `[id]=el.id` should be inside the inner div? I think it should. Thanks – dcg Jun 21 '19 at 15:55
  • @dcg - It depends on what the OP wants to do with the `id`. Or if he wants a template reference variable. That is not clear for me. – ConnorsFan Jun 21 '19 at 15:59
  • Thanks for the comments. I need unique template reference variable – NIDHIN VINCENT Jun 21 '19 at 16:24
  • I dont understand what do you mean with 'unique template reference variable'. Why `[id]=el.id` approach does not work? Maybe this is relevant: https://blog.angularindepth.com/handle-template-reference-variables-with-directives-223081bc70c2 – German Burgardt Jun 21 '19 at 16:45

2 Answers2

-2

Try this :

<div *ngFor="let el of ElementList">
  <ng-template [id]="el.id">
    <div [innerHtml]="el.html"></div>
  </ng-template> 
</div>
Hamza Neffati
  • 155
  • 1
  • 11
  • `ng-template`s are not HTML elements. – ConnorsFan Jun 21 '19 at 15:52
  • 2
    Getting this error Template parse errors: Property binding id not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations". ("
    [ERROR ->]
    ")
    – NIDHIN VINCENT Jun 21 '19 at 16:25
-2

Why not you use @ViewChildren.

<div *ngFor="let el of ElementList">
  <ng-template #elem>
      <div [innerHtml]="el.html"></div>
    </ng-template> 
</div>

In your component class access the template reference variable through ViewChildren, like this

 @ViewChildren(TemplateRef) elem : QueryList<TemplateRef<any>>;

Now you can access templates e.g.

console.log(this.elem.toArray());
Obaid
  • 2,563
  • 17
  • 15