Angular 2 Templates Tutorial - lishman.io
lishman.io Loading..
Style: Blog or IDE

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 and how to use the moduleId property to specify relative URLs.

Quick Tip

In the text below, when you see a word or phrase with this color, click on it to highlight the source code.

Also, take a look at the IDE style to see this tutorial in wide-screen mode. You can always switch back using the Style link at the top of the page.

Show me the IDE style

Inline Templates

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

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

inline.component.ts x
Loading...

Restrictions

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

External Templates

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

external.component.ts x
Loading...
external-template.html x
Loading...

Style Guide

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

Relative URLs

To use a relative path in templateUrl we must include the moduleId. For CommonJS we use the value module.id, and for SystemJS we use __modulename. See Component Relative Paths in Angular 2 for more details on moduleId.

relative.component.ts x
Loading...
external-template.html x
Loading...

Where Next?

More Tutorials

To find out more about Angular components, check out these tutorials.

  • Interpolation - use curly braces and template expressions to output data.
  • Property Binding - update standard properties on the DOM using template expressions.
  • Event Binding - detect standard DOM events and execute 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 - use ngIf, ngSwitch, ngFor, ngClass and ngStyle to transform the DOM.
  • Component Input Output - use @Input and @Output to pass data in to and out of a component.

Source Code

The source code for this tutorial is available on plunker and in the angular-2-templates GitHub repo.