1

I am trying to add html content dynamically into a DIV. Statically this works nicely.

Code which works:

<popover-content #pop1
                 title="Cool Popover"
                 placement="right"
                 [closeOnClickOutside]="true">
  Popped up!!!
</popover-content>

<div>   
    <span>Testing with <span [popover]="pop1" [popoverOnHover]="true">popover</span> as they are not working with DomSanitizer</span>
</div>

Now I need to generate this div content in the backend and then have to dynamically add this inside the div.

Code which doesn't work: HTML:

<popover-content #pop1
                     title="Cool PopOver"
                     placement="right"
                     [closeOnClickOutside]="true">
      Popped up!!!
    </popover-content>

    <div [innerHtml]="message | safeHtml">  
    </div>

.ts file:

this.message = '<span>Testing with <span [popover]="pop1" [popoverOnHover]="true">popover</span> as they are not working with DomSanitizer</span>'

Pipe:

import {Pipe, PipeTransform} from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';

@Pipe({
  name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {

  constructor(private sanitized: DomSanitizer) {
  }

  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }

}

After this also the popover component was not getting called.

While inspecting, I did see that, for dynamically added innerHtml content to DIV, angular is not adding some special behavior to the tag attributes. Why so? And how can I make it work?

Sujoy
  • 802
  • 11
  • 22

1 Answers1

1

With [innerHTML]="..." you can add HTML to the DOM, but Angular won't care what HTML it contains, except for sanitization.

Angular components, directives, event and property bindings only work for HTML added statically to a components template.

What you can do is to compile the HTML with a components template at runtime like explained in How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567