0

I was trying to inject HTML template in an angular component DOM. These HTML template contains a <div>-tag and <script>-tag.

template.html

<div>Some Text</div>
<script>(function() { alert("I am here!"); })()</script>

When I use pure angular to do that within the TestComponent.

test-comp.component.ts

@Component({
  selector: "[test-comp]",
  templateUrl: "./test-comp.component.html",
  styleUrls: ["./test-comp.component.css"]
})
export class TestComponent implements OnInit {
  private _snippet: SafeHtml;

  get snippet(): SafeHtml { return this._snippet; }

  constructor(
    private domSanitizer: DomSanitizer
  ) {}

  ngOnInit() {
    const template: string = require("module/dist/template.html");
    this._snippet = this.domSanitizer.bypassSecurityTrustHtml(template);
  }
}

Component HTML looks like:

test-comp.component.html

<div id="some_id" [innerHTML]="snippets"></div>

This will inject the template correctly within the DOM, but the <script>-tag will not be implemented and it will not alert anything.

If I use jQuery to inject the same template into the same component so the <script>-tag will be implemented and it will alert the text.

test-comp.component.ts

@Component({
  selector: "[test-comp]",
  templateUrl: "./test-comp.component.html",
  styleUrls: ["./test-comp.component.css"]
})
export class TestComponent implements OnInit {
  constructor(
  ) {}

  ngOnInit() {
    const template: string = require("module/dist/template.html");
    $("#some_id").after(template);
  }
}

Is there any explanation for this phenomena? I am interested to know the difference! and why jQuery works?

Note: My question is not duplicated with this question as some poeple mark it, because I am asking: Why it renders with jQuery and not renders with domSanitizer. I am not asking: How to do that?

0

1 Answer 1

0

Angular.io - HTML is the language of the Angular template. Almost all HTML syntax is valid template syntax. The element is a notable exception; it is forbidden, eliminating the risk of script injection attacks. In practice, is ignored and a warning appears in the browser console. See the Security page for details.


However you can bypass security using : DomSanitizer

Sign up to request clarification or add additional context in comments.

1 Comment

I am doing that this.domSanitizer.bypassSecurityTrustHtml(template), but still it does not work! Is that what you mean ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.