0

I have a CMS that stores some HTML contents. In my Angular web app I am getting these contents and injecting them into my templates.

Let's say "myContent" content get from the model is:

<div>Test</div>
<script type="text/javascript">alert("test")</script>

In the component that use this content I have done:

export class PlaceholderComponent implements OnInit  {
  @Input() placeholderKey : string;

  private placeHolderContent : SafeHtml;

  constructor(private modelProvider: ModelProviderService, private sanitizer: DomSanitizer){}

  ngOnInit() {
    if(this.model.placeholders) {
      this.placeHolderContent = this.sanitizer.bypassSecurityTrustHtml(this.model.placeholders[this.placeholderKey]);
    }
  }
}

And in the template of this component

<div [innerHtml]="placeHolderContent"></div>

As a result, the html is correctly injected in the template, including the script tag, but the alert is never executed (note that console.log("test") is not working either).

Do you have a solution to inject HTML with JavaScript that would be run when the component finish loading?

(Note: if I use jquery inside my Angular component to insert HTML in the template it works!)

j3r6me
  • 798
  • 1
  • 5
  • 21
  • Seems similar to [this question](http://stackoverflow.com/questions/38163531/how-to-load-script-file-from-component-html). – Pankaj Parkar Oct 13 '16 at 17:26
  • Using `innerHtml` is not a good practice use `` instead. – Maxime Gélinas Oct 13 '16 at 17:30
  • @PankajParkar it does not seems so, I do not wan tot execute the script form my component. – j3r6me Oct 13 '16 at 17:34
  • @MaximeGélinas could you please provide more details? Here I do not want to have a standard layout into which I inject different templates. I though this was the use of ng-content. – j3r6me Oct 13 '16 at 17:35
  • @jthe even I was trying to load script from template, that I saw similar with me. – Pankaj Parkar Oct 13 '16 at 17:40
  • 1
    It isn't possible for security reasons, ` – Estus Flask Oct 13 '16 at 18:07
  • Why do you have to run script outside of the Angular scope? – Maxime Gélinas Oct 14 '16 at 00:34
  • @MaximeGélinas, our customer can insert html dynamically with the CMS that can interact with other vendors (called through javascript). – j3r6me Oct 14 '16 at 10:03
  • @jthe Its just a supposition but maybe if you inject the HTML after the view's initialisation (after the security check that remove the script tags)? – Maxime Gélinas Oct 16 '16 at 16:54
  • @MaximeGélinas thanks I will try that next time I can work on this. – j3r6me Oct 17 '16 at 13:47

0 Answers0