Angular Mastery: Template Syntax
Tags: webdev, tutorial, javascript, angular
Published: 2019-10-04 13:22:09

---
title: Angular Mastery: Template Syntax
published: true
date: 2019-10-01 10:57:53 UTC
tags: web-development,tutorial,javascript,angular
canonical_url: https://blog.angularindepth.com/angular-mastery-template-syntax-194bffe2ad6f
---

Mastering the Fundamentals of Angular Template Language: Part 1

### Getting Started

**Complexity:** [**Beginner** , **Intermediate** , Advanced, Expert]

**Source Code:** [StackBlitz **🚀**](https://stackblitz.com/edit/erxk-template-syntax)

**Article Goal:** Streamline information from experience and the [Angular Documentation](https://angular.io/guide/template-syntax) to aid in understanding Angular Template Syntax — Utilizing cheat-sheets, code-examples, and focusing on the essentials.

**Article Topics (What We’ll Learn):**

- Expressions & Statements: Guidelines, Rules, and Usages
- Properties & Attributes: How they relate to Data Binding
- Data Binding: Dynamically generating views

### Angular Template Language (ATL)

Angular Template Language is the language used when working with a component-template/html in Angular. We can consider ATL an extension of HTML that allows us to employ _Interpolation_, _Angular Template Expressions & Statements_, _Data Binding_, etc…

To understand the _Angular Template Syntax_, first, we will investigate _Angular Template Expressions and Statements_.

### Expressions & Statements

If you’ve worked with Angular then you’ve likely used an _Angular Template_ _Expression_ or _Angular Template_ S_tatement_ before.

> Angular Template Expressions/Statements will be called expressions and statements for short.

_Expressions_ and _statements_ are essentially a mini-syntax derived from a subset of [JavaScript Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Expressions). [Table A] below may help illuminate the context of when we use one or the other.

Note, in [Table A], **type** refers to a _data binding type_. — We cover _data binding_ in a later section once we have the necessary context of _expressions_, _statements_, and _properties_.

![](https://cdn-images-1.medium.com/max/780/1*aifbepspFomNuLIod1Gsqw.png)<figcaption>Table A</figcaption>

#### Expressions

_Expressions_ have their own syntax and general guidelines that should be followed. — _Expressions_ should be **simple** , **quick** , and have **no side-effects**. These qualities are key to performance. In most cases, _expressions_ will be evaluated every change detection cycle 🔁.

The _expression_ syntax is very similar to JavaScript expressions. — However, there are some limitations to operations that promote side effects. For a [complete list see here](https://angular.io/guide/template-syntax#template-expressions), for syntax examples see [Table B]. See [source code](https://stackblitz.com/edit/erxk-template-syntax?file=src%2Fapp%2Fexpression-examples%2Fexpression-examples.component.html) for corresponding examples of syntax from [Table B].

![](https://cdn-images-1.medium.com/max/916/1*esDUNMii_dnKA8fy1ANzPg.png)<figcaption>Table B</figcaption>

Note, the above examples all use _interpolation_ for consistency. — The results would be the same with _two-way_ [(property)]="expression" and _property binding_ [property]="expression"; as they all use _expressions_.

> Tip: Expressions can utilize a safe-navigation operator to guard against null and undefined _[target]="object?.property"_

#### Statements

When working with event-binding () we are utilizing _statements_. They should be written in a way that is **simple** and usually **has a**  **side-effect**. _Statements_ are _event-driven_, and _events_ usually update state/data from a user action; which is why _statements_ **should** have side effects.

_Statements_ can execute potentially long-running operations and various tasks because they **only run when the bound event fires.**

Compared to _expressions_, similar rules apply to the [syntax of _statements_](https://angular.io/guide/template-syntax#template-statements) with some exceptions. The majority of the time we will simply invoke a method inside of a _statement. — _See [Table C] for syntax examples, see [source code](https://stackblitz.com/edit/erxk-template-syntax?file=src%2Fapp%2Fstatement-examples%2Fstatement-examples.component.ts) for corresponding examples.

![](https://cdn-images-1.medium.com/max/768/1*zAXDATXqFF7qoJAsvf5ecQ.png)<figcaption>Table C</figcaption>

#### Key Points

- Unlike s_tatements_, _expressions_ should **not** execute complex logic, they should always be quick.
- _Expressions_ can utilize the pipe operator |to chain to Angular Pipes. _Statements_ utilize ; and , to chain multiple operations/arguments and cannot use Angular Pipes.
- Both _expressions_ and _statements_ should be simple, short, and concise.

### Properties & Attributes

Before we dive into _Angular Data Binding_, we should understand the differences between [_properties_ and _attributes_](https://angular.io/guide/template-syntax#html-attribute-vs-dom-property).

_Data Binding_ works with **properties** , not _attributes_. Exceptions are _attributes_ such as _aria-\*_ and _svg_. _Properties_ are read from DOM Nodes, whereas _attributes_ are read from HTML Elements. _Attributes_ are used to initialize _properties_ and do not change.

> Caveat, using setAttribute() will change an attribute and re-initialize its corresponding property.

Many _attributes_ have 1:1 relationship with _properties_. For example, on an HTML Input Element, _value_ is the name of an _attribute_ and the name of a _property_. — The GIF below summarizes the above information in action.

![](https://cdn-images-1.medium.com/max/448/1*8nm5bVp_pThxz3Um18rzQA.gif)<figcaption>property “value” changes, attribute “value” does not</figcaption>

#### Key Points

- Angular Data Binding generally works with **properties**
- _Attributes_ and _properties_ are different things, even when they have the same name
- _Attributes_ generally do **not ** change

### Data Binding

[Data Binding](https://angular.io/guide/template-syntax#binding-syntax-an-overview) allows us to dynamically set DOM _properties_ and listen for _events_ simply by declaring a target element _property_/_event_ and writing an _expression_/_statement_. — To better understand data binding, we will use native elements such as _input_ and create our own _components_ with custom bindings.

Data Binding has three categories of **data flow** : _source-to-view_, _view-to-source_, and _two-way_ (_view-to-source-to-view_).

#### One-Way Binding ( **Source-to-View** )

When discussing _source-to-view_ _binding_ we will focus on [**property binding**](https://angular.io/guide/template-syntax#property-binding-property) [property]="expression". As discussed in the previous section, _data binding_ works primarily with _properties_.

Collectively, all five [property]="",[class.css-class]="",[style.css-pro]="",[attr.attribute]="", `{{interpolation}}` are categorized as _source-to-view_.

You may be wondering, where does _interpolation_ fit into _source-to-view_ _binding_? When using _interpolation_, Angular evaluates the _expression_ and writes the interpolated result to an element _property_. — In other words, **Angular converts interpolation into a property binding**.

As shown in the GIF below, all three examples bind to the _textContent property_ and produce the same result.

![](https://cdn-images-1.medium.com/max/556/1*KE0-aQ8MCQB4-XlZ3cYloA.gif)

_Property bindings_ often expect a **specific return type** based on the target DOM _property_. Depending on what type our element/component is expecting, we should return that given type.

{% gist https://gist.github.com/Everduin94/6c89fbfa13a380e14b13692cd7100b08 %}

To summarize, we can visualize _source-to-view binding_ in a username example. Whenever our source properties are updated, the view will reflect those updates on change detection.

![](https://cdn-images-1.medium.com/max/556/1*RqQT672K8YSXLi5J2yhugQ.gif)

#### One-Way Binding (View-to-Source)

View-to-Source, also known as [**Event Binding**](https://angular.io/guide/template-syntax#event-binding-event), connects an _event_ to a _statement_. In other words, when a user fires an action on an element (view-target), it invokes a method inside of our component (data-source)

_Event Binding_ is unique in that it provides the _template variable_ **$event**. This _$event_ variable contains all information regarding the _event_ including any potential updated values.

{% gist https://gist.github.com/Everduin94/7cce285e758aa9994b23296b1d0cb8d2 %}

Using the same username example from earlier, we can visualize our view listening for events and invoking methods from our source on that event.

![](https://cdn-images-1.medium.com/max/764/1*Gxh_MgB1DbElWRq_hr5GEA.gif)<figcaption>$event.target.value abbreviated to $event.value</figcaption>

#### Two-Way Binding (View-to-Source-to-View)

[Two-Way binding](https://angular.io/guide/template-syntax#two-way-binding-) [()], also known as View-to-Source-to-View, is essentially a **shorthand syntax for property binding and event binding together**.

Two-Way Binding follows a semantic pattern in the component where an @Input named **x** and a corresponding @Output named  **xChange.**

{% gist https://gist.github.com/Everduin94/5fd3b6e6c07211fdc683841cb4d5d4c3 %}

The snippet below shows its usage with the t_wo-way Binding_ syntax, as well as explicit syntax using _one-way property binding_ and _one-way event binding_.

{% gist https://gist.github.com/Everduin94/6c7112ff786a1c66b880939d72619cb5 %}

The GIF below attempts to shed light on why/when we would utilize _two-way binding in a component_. Notice, with only _one-way property binding_ (second example), the component value is initialized and updates. However, the external value that was passed in does **not** update when the internal component value updates.

When only _one-way event binding_ is in place (third example), the initial value is never set. Changes are seen in the component, but in this case, we cannot increment or decrement undefined; causing NaN to display.

![](https://cdn-images-1.medium.com/max/446/1*drGATzwXoRiWqjPHikRlNw.gif)<figcaption><em>(countChange)</em>=”externalValue=$event.target.value”</figcaption>

Visualizing the data flow in our username example, our source and view now form a complete circle of invoking the _class/source_ on an event and updating the _template/view_ on change detection:

![](https://cdn-images-1.medium.com/max/776/1*2yXB0_tcv77Y0kicDkU5TQ.gif)

#### Key Points

- Data Binding has three directions: Source-to-View (Property Binding)[], View-to-Source (Event Binding)(), and View-to-Source-to-View (Two-Way Binding)[()]
- Property Binding [] **writes** to the target element
- Event Binding () **listens** to the target element
- Two-Way Binding [()] is just syntactic sugar for Property + Event Binding.

### Conclusion

We’ve covered the basics of leveraging Angular Template Syntax to create dynamic views. — In the next section, we will cover the attribute directives _NgClass_ and _NgStyle_. Thanks for reading!

![](https://cdn-images-1.medium.com/max/438/1*0aeUljGBf1ore8nZElWBCA.png)

### References

- [JavaScript Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators)
- [Expressions](https://angular.io/guide/template-syntax#interpolation-and-template-expressions)
- [Statements](https://angular.io/guide/template-syntax#template-statements)
- [Properties/Attributes](https://angular.io/guide/template-syntax#html-attribute-vs-dom-property)
- [Data Binding](https://angular.io/guide/template-syntax#binding-syntax-an-overview)
- [Property Binding](https://angular.io/guide/template-syntax#property-binding-property)
- [Event Binding](https://angular.io/guide/template-syntax#event-binding-event)
- [Two-Way Binding](https://angular.io/guide/template-syntax#two-way-binding-)

* * *