Angular 2 Templates

Angular's templates mix native HTML with custom elements. In this short tutorial we see how to use inline and external templates.

Updated Nov 2017, Angular version 5.0

Inline Templates

Inline templates are specified directly in the component decorator as shown here.

Template literals with back-ticks allow multi-line strings.

import { Component } from '@angular/core';

    selector: 'app-inline-template',
template: ` <h2>Inline Template</h2> <p> Multi-line inline template using back-ticks </p>`
}) export class InlineComponent {}


Note that the following elements cannot appear in a template: script, html, body and base.

External Template

External templates define the HTML in a separate file and reference this file in templateUrl.

import { Component } from '@angular/core';

    selector: 'app-external-template',
    templateUrl: 'external-template.html'
export class ExternalComponent {}
    <h2>External Template</h2>

Style Guide

The official Angular Style Guide recommends that templates are extracted to their own files when the template contains more than 3 lines

Where Next?

To find out more about Angular and TypeScript, check out these tutorials.

  • Hello World - Implement a super-simple <hello-world> custom element using an Angular and TypeScript.
  • The Angular with TypeScript Tutorial - includes examples of components, template syntax, property binding, event binding, bootstrapping and more.
  • Configuration - Configure Angular and TypeScript to download dependencies from node modules or a CDN, and to compile the TypeScript during development or in the browser at runtime.
  • Interpolation - use curly braces and template expressions to output data on the page.
  • Property Binding - bind to DOM properties using square brackets and template expressions.
  • Event Binding - handle DOM events using parentheses and template statements.
  • Two-way Binding - combine property and event binding to create two-way binding with ngModel.
  • Input Binding - bind to <input> fields such as text, textarea, checkbox, radio and select.
  • Built-in Directives - see how to use built-in directives ngIf, ngSwitch, ngFor, ngClass and ngStyle.
  • Component Input Output - use @Input and @Output to pass data in to and out of a component.
  • Angular Router - Use the Angular router to navigate between components when the user clicks a link.
  • Nested Child Routes - An example of how child routes allow navigation between multiple views when a user clicks a link in a sub-menu.