Angular Templates

Angular Templates and Interpolation

In Angular, a template is simply a chunk of HTML that tells the framework how to render the component.

Angular significantly enhances standard HTML by allowing you to inject dynamic data directly into the markup.

This process of embedding dynamic JavaScript expressions into HTML is called "Interpolation".


The Mustache Syntax

To perform interpolation in an Angular template, you use double curly braces: {{ }}.

This is often affectionately referred to as the "Mustache syntax".

Angular evaluates the expression inside the mustaches and replaces it with a string value.

Interpolation Example:

<!-- Inside app.component.html -->
<h1>Welcome to {{ title }}!</h1>
<p>The current year is {{ currentYear }}</p>

Evaluating Expressions

The code inside the double curly braces does not just have to be a simple variable name.

You can evaluate standard JavaScript math, concatenate strings, and even call component methods!

Expression Examples:

<!-- Simple math calculation -->
<p>2 + 2 equals {{ 2 + 2 }}</p>

<!-- Calling a method from the TypeScript class --> <p>Greeting: {{ getGreetingMessage() }}</p>

However, there are restrictions: you cannot use assignments (=) or complex logic like if/else inside the interpolation braces.


Inline vs External Templates

When you define a component in TypeScript, you must link it to a template.

If your HTML is extremely small, you can write it directly inside the @Component decorator using the template property.

For larger blocks of HTML, you should link to an external .html file using the templateUrl property.

Inline Template Example:

@Component({
  selector: 'app-mini',
  // Notice the backticks allowing for multi-line HTML
  template: `
    <div class="box">
      <h3>{{ shortTitle }}</h3>
    </div>
  `
})
export class MiniComponent {
  shortTitle = 'Inline HTML Rules!';
}

Keeping large HTML separate makes your project far easier to organize and maintain.


Exercise 1 of 2

?

Which syntax is used to interpolate data directly into an Angular HTML template?

Exercise 2 of 2

?

Can you write complex if/else statements directly inside the {{ }} interpolation tags?