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?