'How to parse a html string with structural directive in angular

I am trying to parse a html string with structural directive inside ng-template. But it is displayed as a string. My exceptions was the structural directive will iterate three times and it will show three li. How can I achieve that?

Here is my code

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  data = `<div><li *ngFor="let d of [1,2,3]">{{d}}</li> </div>`;
}
<section>
  <ng-container
    [ngTemplateOutlet]="template"
    [ngTemplateOutletContext]="{ html: data }"
  ></ng-container>
</section>

<ng-template #template let-html="html">
  {{ html }}
</ng-template>

Sample code here



Solution 1:[1]

Would suggest you perform the interpolation on the controller itself, I don't think interpolation works on string insertion.

import { Component, OnInit, Sanitizer, VERSION } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  data: any = `<div>${[1, 2, 3].map((x) => `<li>${x}</li>`).join('')}</div>`;

  constructor(private sanitizer: DomSanitizer) {}

  ngOnInit() {
    this.data = this.sanitizer.bypassSecurityTrustHtml(this.data);
  }
}

html

<section>
  <ng-container
    [ngTemplateOutlet]="template"
    [ngTemplateOutletContext]="{ html: data }"
  ></ng-container>
</section>

<ng-template #template let-html="html" >
  <div [innerHTML]="html"></div>
</ng-template>

stackblitz

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Naren Murali