Search code examples
angular-template

Angular, <template> element and #document-fragment


  1. If I add <template><img src="url1" /></template> in any basic HTML page, the img resource at url1 is not downloaded, and according to Chrome DevTools a document-fragment containing the img element is created

enter image description here

  1. If I add <template><img src="url2" /></template> to any Angular component template file, the img resource at url2 is downloaded, and the DOM contains a template element with an empty document-fragment and a img element as siblings

enter image description here

How can I add the <template ... snippet to a Angular template as in 2), but have the same result as in 1)?

ngNonBindable on the <template> element or the <img> element seems to have no effect.
I am using Angular 10.
I need to do this because I am using a 3rd party library which needs to be configured using a <template> element with specific token as img src value which will be replaced internally.


Solution

  • <template> HTML tags are definitely rendered differently in Angular.

    Use the [innerHTML] binding to get your template to render the content like it does outside of Angular. When testing your example, I needed to define the img HTML as a separate variable in the component as follows so as to not be sanitized by Angular:

    export class SomeComponent {
      htmlStr: string = '<img src="url1" />';
    }
    

    source: https://www.digitalocean.com/community/tutorials/angular-innerhtml-binding-angular

    Now use the htmlStr variable in the <template> with [innerHTML]:

    <template [innerHTML]="htmlStr"> </template>
    

    These were additional sources for my answer: Angular 6 create HTMLElement from HTMLTemplateElement https://dev.to/patricksevat/using-web-components-custom-elements-in-template-tag-htmltemplateelement-using-angular-1ik8