# Template Syntax The Angular application manages what the user sees and can do, achieving this through the interaction of a component class instance (the *component*) and its user-facing template. You may be familiar with the component/template duality from your experience with model-view-controller (MVC) or model-view-viewmodel (MVVM). In Angular, the component plays the part of the controller/viewmodel, and the template represents the view. This page is a comprehensive technical reference to the Angular template language. It explains basic principles of the template language and describes most of the syntax that you'll encounter elsewhere in the documentation. Many code snippets illustrate the points and concepts, all of them available in the . {@a html} ## HTML in templates HTML is the language of the Angular template. Almost all HTML syntax is valid template syntax. The ` Syntax" is the interpolated evil title. "Template alert("evil never sleeps")Syntax" is the property bound evil title. ```
{@a other-bindings} ## Attribute, class, and style bindings The template syntax provides specialized one-way bindings for scenarios less well-suited to property binding. To see attribute, class, and style bindings in a functioning app, see the especially for this section. ### Attribute binding Set the value of an attribute directly with an **attribute binding**. This is the only exception to the rule that a binding sets a target property and the only binding that creates and sets an attribute. Usually, setting an element property with a [property binding](guide/template-syntax#property-binding) is preferable to setting the attribute with a string. However, sometimes there is no element property to bind, so attribute binding is the solution. Consider the [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) and [SVG](https://developer.mozilla.org/en-US/docs/Web/SVG). They are purely attributes, don't correspond to element properties, and don't set element properties. In these cases, there are no property targets to bind to. Attribute binding syntax resembles property binding, but instead of an element property between brackets, start with the prefix `attr`, followed by a dot (`.`), and the name of the attribute. You then set the attribute value, using an expression that resolves to a string, or remove the attribute when the expression resolves to `null`. One of the primary use cases for attribute binding is to set ARIA attributes, as in this example:
#### `colspan` and `colSpan` Notice the difference between the `colspan` attribute and the `colSpan` property. If you wrote something like this: <tr><td colspan="{{1 + 1}}">Three-Four</td></tr> You'd get this error: Template parse errors: Can't bind to 'colspan' since it isn't a known native property As the message says, the `` element does not have a `colspan` property. This is true because `colspan` is an attribute—`colSpan`, with a capital `S`, is the corresponding property. Interpolation and property binding can set only *properties*, not attributes. Instead, you'd use property binding and write it like this:

### Class binding Add and remove CSS class names from an element's `class` attribute with a **class binding**. Here's how to set the attribute without binding in plain HTML: ```html
Item clearance special
``` Class binding syntax resembles property binding, but instead of an element property between brackets, start with the prefix `class`, optionally followed by a dot (`.`) and the name of a CSS class: `[class.class-name]`. You can replace that with a binding to a string of the desired class names; this is an all-or-nothing, replacement binding. You can also add append a class to an element without overwriting the classes already on the element: Finally, you can bind to a specific class name. Angular adds the class when the template expression evaluates to truthy. It removes the class when the expression is falsy. While this technique is suitable for toggling a single class name, consider the [`NgClass`](guide/template-syntax#ngClass) directive when managing multiple class names at the same time.
### Style binding You can set inline styles with a **style binding**. Style binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix `style`, followed by a dot (`.`) and the name of a CSS style property: `[style.style-property]`. Some style binding styles have a unit extension. The following example conditionally sets the font size in “em” and “%” units . **This technique is suitable for setting a single style, but consider the [`NgStyle`](guide/template-syntax#ngStyle) directive when setting several inline styles at the same time.**
Note that a _style property_ name can be written in either [dash-case](guide/glossary#dash-case), as shown above, or [camelCase](guide/glossary#camelcase), such as `fontSize`.

{@a event-binding} ## Event binding `(event)` Event binding allows you to listen for certain events such as keystrokes, mouse movements, clicks, and touches. For an example demonstrating all of the points in this section, see the event binding example. Angular event binding syntax consists of a **target event** name within parentheses on the left of an equal sign, and a quoted template statement on the right. The following event binding listens for the button's click events, calling the component's `onSave()` method whenever a click occurs:
Syntax diagram
### Target event As above, the target is the button's click event. Alternatively, use the `on-` prefix, known as the canonical form: Element events may be the more common targets, but Angular looks first to see if the name matches an event property of a known directive, as it does in the following example: If the name fails to match an element event or an output property of a known directive, Angular reports an “unknown directive” error. ### *$event* and event handling statements In an event binding, Angular sets up an event handler for the target event. When the event is raised, the handler executes the template statement. The template statement typically involves a receiver, which performs an action in response to the event, such as storing a value from the HTML control into a model. The binding conveys information about the event. This information can include data values such as an event object, string, or number named `$event`. The target event determines the shape of the `$event` object. If the target event is a native DOM element event, then `$event` is a [DOM event object](https://developer.mozilla.org/en-US/docs/Web/Events), with properties such as `target` and `target.value`. Consider this example: This code sets the `` `value` property by binding to the `name` property. To listen for changes to the value, the code binds to the `input` event of the `` element. When the user makes changes, the `input` event is raised, and the binding executes the statement within a context that includes the DOM event object, `$event`. To update the `name` property, the changed text is retrieved by following the path `$event.target.value`. If the event belongs to a directive—recall that components are directives—`$event` has whatever shape the directive produces. ### Custom events with `EventEmitter` Directives typically raise custom events with an Angular [EventEmitter](api/core/EventEmitter). The directive creates an `EventEmitter` and exposes it as a property. The directive calls `EventEmitter.emit(payload)` to fire an event, passing in a message payload, which can be anything. Parent directives listen for the event by binding to this property and accessing the payload through the `$event` object. Consider an `ItemDetailComponent` that presents item information and responds to user actions. Although the `ItemDetailComponent` has a delete button, it doesn't know how to delete the hero. It can only raise an event reporting the user's delete request. Here are the pertinent excerpts from that `ItemDetailComponent`: The component defines a `deleteRequest` property that returns an `EventEmitter`. When the user clicks *delete*, the component invokes the `delete()` method, telling the `EventEmitter` to emit an `Item` object. Now imagine a hosting parent component that binds to the `deleteRequest` event of the `ItemDetailComponent`. When the `deleteRequest` event fires, Angular calls the parent component's `deleteItem()` method, passing the *item-to-delete* (emitted by `ItemDetail`) in the `$event` variable. ### Template statements have side effects Though [template expressions](guide/template-syntax#template-expressions) shouldn't have [side effects](guide/template-syntax#avoid-side-effects), template statements usually do. The `deleteItem()` method does have a side effect: it deletes an item. Deleting an item updates the model, and depending on your code, triggers other changes including queries and saving to a remote server. These changes propagate through the system and ultimately display in this and other views.
{@a two-way} ## Two-way binding `[(...)]` Two-way binding gives your app a way to share data between a component class and its template. For a demonstration of the syntax and code snippets in this section, see the two-way binding example. ### Basics of two-way binding Two-way binding does two things: 1. Sets a specific element property. 1. Listens for an element change event. Angular offers a special _two-way data binding_ syntax for this purpose, `[()]`. The `[()]` syntax combines the brackets of property binding, `[]`, with the parentheses of event binding, `()`.
[( )] = banana in a box
Visualize a *banana in a box* to remember that the parentheses go _inside_ the brackets.
The `[()]` syntax is easy to demonstrate when the element has a settable property called `x` and a corresponding event named `xChange`. Here's a `SizerComponent` that fits this pattern. It has a `size` value property and a companion `sizeChange` event: The initial `size` is an input value from a property binding. Clicking the buttons increases or decreases the `size`, within min/max value constraints, and then raises, or emits, the `sizeChange` event with the adjusted size. Here's an example in which the `AppComponent.fontSizePx` is two-way bound to the `SizerComponent`: The `AppComponent.fontSizePx` establishes the initial `SizerComponent.size` value. Clicking the buttons updates the `AppComponent.fontSizePx` via the two-way binding. The revised `AppComponent.fontSizePx` value flows through to the _style_ binding, making the displayed text bigger or smaller. The two-way binding syntax is really just syntactic sugar for a _property_ binding and an _event_ binding. Angular desugars the `SizerComponent` binding into this: The `$event` variable contains the payload of the `SizerComponent.sizeChange` event. Angular assigns the `$event` value to the `AppComponent.fontSizePx` when the user clicks the buttons. ## Two-way binding in forms The two-way binding syntax is a great convenience compared to separate property and event bindings. It would be convenient to use two-way binding with HTML form elements like `` and `` element's `value` property and `input` event: To streamline the syntax, the `ngModel` directive hides the details behind its own `ngModel` input and `ngModelChange` output properties: The `ngModel` data property sets the element's value property and the `ngModelChange` event property listens for changes to the element's value. #### `NgModel` and value accessors The details are specific to each kind of element and therefore the `NgModel` directive only works for an element supported by a [ControlValueAccessor](api/forms/ControlValueAccessor) that adapts an element to this protocol. Angular provides *value accessors* for all of the basic HTML form elements and the [Forms](guide/forms) guide shows how to bind to them. You can't apply `[(ngModel)]` to a non-form native element or a third-party custom component until you write a suitable value accessor. For more information, see the API documentation on [DefaultValueAccessor](https://angular.io/api/forms/DefaultValueAccessor). You don't need a value accessor for an Angular component that you write because you can name the value and event properties to suit Angular's basic [two-way binding syntax](guide/template-syntax#two-way) and skip `NgModel` altogether. The `sizer` in the [Two-way Binding](guide/template-syntax#two-way) section is an example of this technique. Separate `ngModel` bindings are an improvement over binding to the element's native properties, but you can streamline the binding with a single declaration using the `[(ngModel)]` syntax: This `[(ngModel)]` syntax can only _set_ a data-bound property. If you need to do something more, you can write the expanded form; for example, the following changes the `` value to uppercase: Here are all variations in action, including the uppercase version:
NgModel variations

{@a structural-directives} ## Built-in _structural_ directives Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, and manipulating the host elements to which they are attached. This section is an introduction to the common built-in structural directives: * [`NgIf`](guide/template-syntax#ngIf)—conditionally creates or destroys subviews from the template. * [`NgFor`](guide/template-syntax#ngFor)—repeat a node for each item in a list. * [`NgSwitch`](guide/template-syntax#ngSwitch)—a set of directives that switch among alternative views.
The deep details of structural directives are covered in the [Structural Directives](guide/structural-directives) guide, which explains the following: * Why you [prefix the directive name with an asterisk (\*)](guide/structural-directives#the-asterisk--prefix). * Using [``](guide/structural-directives#ngcontainer "") to group elements when there is no suitable host element for the directive. * How to write your own structural directive. * That you can only apply [one structural directive](guide/structural-directives#one-per-element "one per host element") to an element.

{@a ngIf} ### NgIf You can add or remove an element from the DOM by applying an `NgIf` directive to a host element. Bind the directive to a condition expression like `isActive` in this example.
Don't forget the asterisk (`*`) in front of `ngIf`. For more information on the asterisk, see the [asterisk (*) prefix](guide/structural-directives#the-asterisk--prefix) section of [Structural Directives](guide/structural-directives).
When the `isActive` expression returns a truthy value, `NgIf` adds the `ItemDetailComponent` to the DOM. When the expression is falsy, `NgIf` removes the `ItemDetailComponent` from the DOM, destroying that component and all of its sub-components. #### Show/hide vs. `NgIf` Hiding an element is different from removing it with `NgIf`. For comparison, the following example shows how to control the visibility of an element with a [class](guide/template-syntax#class-binding) or [style](guide/template-syntax#style-binding) binding. When you hide an element, that element and all of its descendants remain in the DOM. All components for those elements stay in memory and Angular may continue to check for changes. You could be holding onto considerable computing resources and degrading performance unnecessarily. `NgIf` works differently. When `NgIf` is `false`, Angular removes the element and its descendants from the DOM. It destroys their components, freeing up resources, which results in a better user experience. If you are hiding large component trees, consider `NgIf` as a more efficient alternative to showing/hiding.
**Note:** For more information on `NgIf` and `ngIfElse`, see the [API documentation about NgIf](api/common/NgIf).
#### Guard against null Another advantage of `ngIf` is that you can use it to guard against null. Show/hide is best suited for very simple use cases, so when you need a guard, opt instead for `ngIf`. Angular will throw an error if a nested expression tries to access a property of `null`. The following shows `NgIf` guarding two `
`s. The `currentCustomer` name appears only when there is a `currentCustomer`. The `nullCustomer` will not be displayed as long as it is `null`.
See also the [safe navigation operator](guide/template-syntax#safe-navigation-operator "Safe navigation operator (?.)") below.

{@a ngFor} ### `NgFor` `NgFor` is a repeater directive—a way to present a list of items. You define a block of HTML that defines how a single item should be displayed and then you tell Angular to use that block as a template for rendering each item in the list. Here is an example of `NgFor` applied to a simple `
`: You can also apply an `NgFor` to a component element, as in this example:
Don't forget the asterisk (`*`) in front of `ngFor`.
The text assigned to `*ngFor` is the instruction that guides the repeater process. {@a microsyntax} #### `*ngFor` microsyntax The string assigned to `*ngFor` is not a [template expression](guide/template-syntax#template-expressions). Rather, it's a *microsyntax*—a little language of its own that Angular interprets. The string `"let item of items"` means: > *Take each item in the `items` array, store it in the local `item` looping variable, and make it available to the templated HTML for each iteration.* Angular translates this instruction into an `` around the host element, then uses this template repeatedly to create a new set of elements and bindings for each `item` in the list. For more information about microsyntax, see the [Structural Directives](guide/structural-directives#microsyntax) guide. {@a template-input-variable} {@a template-input-variables} #### Template input variables The `let` keyword before `item` creates a template input variable called `item`. The `ngFor` directive iterates over the `items` array returned by the parent component's `items` property and sets `item` to the current item from the array during each iteration. Reference `item` within the `ngFor` host element as well as within its descendants to access the item's properties. The following example references `item` first in an interpolation and then passes in a binding to the `item` property of the `` component. For more information about template input variables, see [Structural Directives](guide/structural-directives#template-input-variable). #### `*ngFor` with `index` The `index` property of the `NgFor` directive context returns the zero-based index of the item in each iteration. You can capture the `index` in a template input variable and use it in the template. The next example captures the `index` in a variable named `i` and displays it with the item name.
`NgFor` is implemented by the `NgForOf` directive. Read more about the other `NgForOf` context values such as `last`, `even`, and `odd` in the [NgForOf API reference](api/common/NgForOf).
{@a trackBy} #### *ngFor with `trackBy` If you use `NgFor` with large lists, a small change to one item, such as removing or adding an item, can trigger a cascade of DOM manipulations. For example, re-querying the server could reset a list with all new item objects, even when those items were previously displayed. In this case, Angular sees only a fresh list of new object references and has no choice but to replace the old DOM elements with all new DOM elements. You can make this more efficient with `trackBy`. Add a method to the component that returns the value `NgFor` should track. In this case, that value is the hero's `id`. If the `id` has already been rendered, Angular keeps track of it and doesn't re-query the server for the same `id`. In the microsyntax expression, set `trackBy` to the `trackByItems()` method. Here is an illustration of the `trackBy` effect. "Reset items" creates new items with the same `item.id`s. "Change ids" creates new items with new `item.id`s. * With no `trackBy`, both buttons trigger complete DOM element replacement. * With `trackBy`, only changing the `id` triggers element replacement.
Animation of trackBy

{@a ngSwitch} ## The `NgSwitch` directives NgSwitch is like the JavaScript `switch` statement. It displays one element from among several possible elements, based on a switch condition. Angular puts only the selected element into the DOM. `NgSwitch` is actually a set of three, cooperating directives: `NgSwitch`, `NgSwitchCase`, and `NgSwitchDefault` as in the following example.
Animation of NgSwitch
`NgSwitch` is the controller directive. Bind it to an expression that returns the *switch value*, such as `feature`. Though the `feature` value in this example is a string, the switch value can be of any type. **Bind to `[ngSwitch]`**. You'll get an error if you try to set `*ngSwitch` because `NgSwitch` is an *attribute* directive, not a *structural* directive. Rather than touching the DOM directly, it changes the behavior of its companion directives. **Bind to `*ngSwitchCase` and `*ngSwitchDefault`**. The `NgSwitchCase` and `NgSwitchDefault` directives are _structural_ directives because they add or remove elements from the DOM. * `NgSwitchCase` adds its element to the DOM when its bound value equals the switch value and removes its bound value when it doesn't equal the switch value. * `NgSwitchDefault` adds its element to the DOM when there is no selected `NgSwitchCase`. The switch directives are particularly useful for adding and removing *component elements*. This example switches among four `item` components defined in the `item-switch.components.ts` file. Each component has an `item` [input property](guide/template-syntax#inputs-outputs "Input property") which is bound to the `currentItem` of the parent component. Switch directives work as well with native elements and web components too. For example, you could replace the `` switch case with the following.
{@a template-reference-variable} {@a template-reference-variables--var-} {@a ref-vars} {@a ref-var} ## Template reference variables (`#var`) A **template reference variable** is often a reference to a DOM element within a template. It can also refer to a directive (which contains a component), an element, [TemplateRef](api/core/TemplateRef), or a web component. For a demonstration of the syntax and code snippets in this section, see the template reference variables example. Use the hash symbol (#) to declare a reference variable. The following reference variable, `#phone`, declares a `phone` variable on an `` element. You can refer to a template reference variable anywhere in the component's template. Here, a `