0

I am using external library that returns html and scripts from the server. Sample response looks like:

<div>
   1. Some text
</div>
<script>
function transform()
{
 //some js code
}
function calculate()
{
 //some js code
}

I am trying to insert this code into angular view. I have tried through DomSanitizer and ElementRef but does not work. Returned code from server is quiete complicated, has many js functions.

justme
  • 316
  • 3
  • 13

1 Answers1

0

Edit The code below should work:

import { Component, ElementRef } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name: string;
  constructor(private elementRef: ElementRef) {}

  func() {
    let b = document.createElement("div");
    b.innerHTML = "<h3>Returned html<h3>";

    let s = document.createElement("script");
    s.type = "text/javascript";
    s.innerHTML = "console.log('done');"; //inline script
    // s.src = "https://somesite.com/script.js"; // src script

    b.appendChild(s);

    this.elementRef.nativeElement.appendChild(b);
  }
}
Test Doe
  • 54
  • 5
  • Yes, I did this exactly the way you described. Html part was rendered successfully but scripts are not rendered, however scripts are visible in browser when inspecting. – justme Mar 22 '21 at 17:09
  • Interesting, do you mind pasting the essential code in a stackblitz so that we can take a better look? – Test Doe Mar 22 '21 at 17:13
  • Also, there are multiple ways of bypassing the DOM sanitizer, see if this helps https://stackoverflow.com/questions/50168080/i-am-using-http-post-to-get-a-response-and-setting-my-div-innerhtml-response – Test Doe Mar 22 '21 at 17:17
  • Here you are: https://stackblitz.com/edit/angular-5pxfce?file=src/app/app.component.ts – justme Mar 22 '21 at 17:19
  • Check this out, it should work https://stackblitz.com/edit/angular-hkcump?file=src%2Fapp%2Fapp.component.ts – Test Doe Mar 22 '21 at 17:36
  • Is it possible to do the same with code: ? – justme Mar 22 '21 at 17:55
  • Yes, I edited the stackblitz. Check it out. – Test Doe Mar 22 '21 at 17:57