0

I am developing dynamic template creation based on following example. example but i can't get html output. i.e) dynamic content. ts file:

@Component({
  selector: 'product-item',
  template: `
    <div class="product">
      <ng-container *compile="template; context: this"></ng-container>
    </div>`,
})
export class DynamicItemComponent {
        
  @Input() content: string = `<a (click)='changeEditor('TEXT')'>Click me</a>`;  
  @Input() template: string = `{{content}}`;
    
}

Html:

<product-item [content]="selectedTemplate.content"></product-item>

how can i get html output. i already used safethtml pipe, that is also not working. Thanks in advance.

Community
  • 1
  • 1
Balasubramanian
  • 700
  • 7
  • 26

1 Answers1

0

You can create HTML Template using ng-template directive.

<ng-template #anchorRef>
   <a (click)="changeEditor('TEXT')">Click me</a>
</ng-template>

You can pass this templateRef as input to child component using @Input decorator.

Child Component:

Using *ngTemplateOutlet structural directive,

@Component({
  selector: 'hello',
  template: `
  <h1>Hello !</h1>
  <ng-container *ngTemplateOutlet="name"></ng-container>
  `,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: TemplateRef<any>;
}
Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27
  • Thanks. but html content is dynamic, so cant use ng-template. my question is. when i bind html content in template it is working, but above example not working. – Balasubramanian Nov 26 '18 at 12:37
  • for dynamic HTML content, you can use [innerHTML] attribute binding. https://stackoverflow.com/questions/49013217/how-to-render-string-with-html-tags-in-angular-4 – Suresh Kumar Ariya Nov 26 '18 at 12:46
  • if i go with innerhtml, i cant get anger tag events. https://stackoverflow.com/questions/53447577/a-tag-click-event-inside-innerhtml-in-angular-6 – Balasubramanian Nov 26 '18 at 13:19