Mastering Angular Components
上QQ阅读APP看书,第一时间看更新

Template elements

Template elements allow you to define regions within your HTML, which will not be rendered by the browser. You can then instantiate these document fragments with JavaScript and then place the resulting DOM within your document.

While the browser is actually parsing the template content, it only does so in order to validate the HTML. Any immediate actions that the parser would usually execute will not be taken. Within the content of template elements, images will not be loaded and scripts won't be executed. Only after a template is instantiated will the parser take the necessary actions, as follows:

<body> 
<template id="template">
<h1>This is a template!</h1>
</template>
</body>

This simple HTML example of a template element won't display the heading on your page. As the heading is inside a template element, we first need to instantiate the template and add the resulting DOM into our document:

var template = document.querySelector('#template'); 
var instance = document.importNode(template.content, true);
document.body.appendChild(instance);

Using these three lines of JavaScript, we can instantiate the template and append it into our document.

Template elements are used by Angular in order to instantiate dynamic parts of your user interface. This will be the case while conditionally rendering parts of your template using the ngIf directive, or by repeating a template using the ngFor directive.