Template in Angular – an introduction

In this article, we’ll discuss template in Angular.

What is a template in Angular?

A template contains the presentation of a component. That is, how a component looks or rendered in browser is defined in a template. Angular template is regular HTML code to which Angular constructs can be added for extra features. Angular template renders a view in browser.

Let us understand this with an example. Suppose, for header of web application we create a header component. Then, how the header will look like in browser is defined by a template.

When we create a component using Angular CLI, template file <component-name>.component.html is created for us. For example, when we create a new application, app.component.html file is created by Angular CLI.

Template is declared as an external file by templateUrl property of Component decorator or as inline template by template property.

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],

In this example, app.component.html is the template which contains presentation logic of angular template.

The default template code generated by Angular CLI looks like this:

<h1>App Component works!</h1>

What we can and can’t write in Angular template?

  • An Angular template is valid HTML code. So we have to keep in mind to properly close the open HTML tags. Every valid HTML code is valid Angular template except few restrictions explained later.
  • Since a component represents a part of an application but not the entire application, we should not use <html>, <body>, or <base> in template.
  • As a prevention of script injection attacks, <script> elements are not supported in Angular template and ignored by Angular by raising a warning to the browser console.
  • In addition to HTML code, Angular template can have much more functionality. For example, we can use conditions to hide or show a part of HTML in template. We can use loops, manipulate DOM and much more.