# 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. ### Attribute binding You can 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. This is the only binding that creates and sets an attribute.
This guide stresses repeatedly that setting an element property with a property binding is always preferred to setting the attribute with a string. Why does Angular offer attribute binding? **You must use attribute binding when there is no element property to bind.** Consider the [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA), [SVG](https://developer.mozilla.org/en-US/docs/Web/SVG), and table span attributes. They are pure attributes. They do not correspond to element properties, and they do not set element properties. There are no property targets to bind to. This fact becomes obvious when you write something like this. <tr><td colspan="{{1 + 1}}">Three-Four</td></tr> And you 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. It has the "colspan" *attribute*, but interpolation and property binding can set only *properties*, not attributes. You need attribute bindings to create and bind to such attributes. Attribute binding syntax resembles property binding. 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. Bind `[attr.colspan]` to a calculated value: Here's how the table renders:
One-Two
FiveSix
One of the primary use cases for attribute binding is to set ARIA attributes, as in this example:
### Class binding You can add and remove CSS class names from an element's `class` attribute with a **class binding**. Class binding syntax resembles property binding. 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]`. The following examples show how to add and remove the application's "special" class with class bindings. Here's how to set the attribute without binding: You can replace that with a binding to a string of the desired class names; this is an all-or-nothing, replacement binding. 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 is a fine way to toggle a single class name, the [NgClass directive](guide/template-syntax#ngClass) is usually preferred 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 .
While this is a fine way to set a single style, the [NgStyle directive](guide/template-syntax#ngStyle) is generally preferred 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 ( [(...)] ) You often want to both display a data property and update that property when the user makes changes. On the element side that takes a combination of setting a specific element property and listening for an element change event. Angular offers a special _two-way data binding_ syntax for this purpose, **`[(x)]`**. The `[(x)]` syntax combines the brackets of _property binding_, `[x]`, with the parentheses of _event binding_, `(x)`.
[( )] = banana in a box
Visualize a *banana in a box* to remember that the parentheses go _inside_ the brackets.
The `[(x)]` 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 the 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 values constraints, and then raises (_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. Clearly 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. That's cumbersome. Who can remember which element property to set and which element event emits user changes? How do you extract the currently displayed text from the input box so you can update the data property? Who wants to look that up each time? That `ngModel` directive hides these onerous 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. 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. The `` box is one of those elements. 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*, a technique that is beyond the scope of this guide. 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` shown above](guide/template-syntax#two-way) is an example of this technique.
Separate `ngModel` bindings is an improvement over binding to the element's native properties. You can do better. You shouldn't have to mention the data property twice. Angular should be able to capture the component's data property and set it with a single declaration, which it can with the `[(ngModel)]` syntax: Is `[(ngModel)]` all you need? Is there ever a reason to fall back to its expanded form? The `[(ngModel)]` syntax can only _set_ a data-bound property. If you need to do something more or something different, you can write the expanded form. The following contrived example forces the input 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. The deep details of structural directives are covered in the [_Structural Directives_](guide/structural-directives) guide where you'll learn: * why you [_prefix the directive name with an asterisk_ (\*)](guide/structural-directives#asterisk "The * in *ngIf"). * to use [``](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. _This_ section is an introduction to the common structural directives: * [`NgIf`](guide/template-syntax#ngIf) - conditionally add or remove an element from the DOM * [`NgSwitch`](guide/template-syntax#ngSwitch) - a set of directives that switch among alternative views * [NgForOf](guide/template-syntax#ngFor) - repeat a template for each item in a list
{@a ngIf} ### NgIf You can add or remove an element from the DOM by applying an `NgIf` directive to that element (called the _host element_). Bind the directive to a condition expression like `isActive` in this example.
Don't forget the asterisk (`*`) in front of `ngIf`.
When the `isActive` expression returns a truthy value, `NgIf` adds the `HeroDetailComponent` to the DOM. When the expression is falsy, `NgIf` removes the `HeroDetailComponent` from the DOM, destroying that component and all of its sub-components. #### Show/hide is not the same thing You can control the visibility of an element with a [class](guide/template-syntax#class-binding) or [style](guide/template-syntax#style-binding) binding: Hiding an element is quite different from removing an element with `NgIf`. When you hide an element, that element and all of its descendents 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, for something the user can't see. When `NgIf` is `false`, Angular removes the element and its descendents from the DOM. It destroys their components, potentially freeing up substantial resources, resulting in a more responsive user experience. The show/hide technique is fine for a few elements with few children. You should be wary when hiding large component trees; `NgIf` may be the safer choice. #### Guard against null The `ngIf` directive is often used to guard against null. Show/hide is useless as a guard. Angular will throw an error if a nested expression tries to access a property of `null`. Here we see `NgIf` guarding two `
`s. The `currentHero` name will appear only when there is a `currentHero`. The `nullHero` will never be displayed.
See also the [_safe navigation operator_](guide/template-syntax#safe-navigation-operator "Safe navigation operator (?.)") described below.

{@a ngFor} ### NgForOf `NgForOf` 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. You tell Angular to use that block as a template for rendering each item in the list. Here is an example of `NgForOf` applied to a simple `
`: You can also apply an `NgForOf` 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). It's a *microsyntax* — a little language of its own that Angular interprets. The string `"let hero of heroes"` means: > *Take each hero in the `heroes` array, store it in the local `hero` looping variable, and make it available to the templated HTML for each iteration.* Angular translates this instruction into a `` around the host element, then uses this template repeatedly to create a new set of elements and bindings for each `hero` in the list. Learn about the _microsyntax_ in the [_Structural Directives_](guide/structural-directives#microsyntax) guide. {@a template-input-variable} {@a template-input-variables} ### Template input variables The `let` keyword before `hero` creates a _template input variable_ called `hero`. The `NgForOf` directive iterates over the `heroes` array returned by the parent component's `heroes` property and sets `hero` to the current item from the array during each iteration. You reference the `hero` input variable within the `NgForOf` host element (and within its descendants) to access the hero's properties. Here it is referenced first in an interpolation and then passed in a binding to the `hero` property of the `` component. Learn more about _template input variables_ in the [_Structural Directives_](guide/structural-directives#template-input-variable) guide. #### *ngFor with _index_ The `index` property of the `NgForOf` 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 hero name like this.
`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_ The `NgForOf` directive may perform poorly, especially with large lists. A small change to one item, an item removed, or an item added can trigger a cascade of DOM manipulations. For example, re-querying the server could reset the list with all new hero objects. Most, if not all, are previously displayed heroes. *You* know this because the `id` of each hero hasn't changed. But Angular sees only a fresh list of new object references. It has no choice but to tear down the old DOM elements and insert all new DOM elements. Angular can avoid this churn with `trackBy`. Add a method to the component that returns the value `NgForOf` _should_ track. In this case, that value is the hero's `id`. In the microsyntax expression, set `trackBy` to this method. Here is an illustration of the _trackBy_ effect. "Reset heroes" creates new heroes with the same `hero.id`s. "Change ids" creates new heroes with new `hero.id`s. * With no `trackBy`, both buttons trigger complete DOM element replacement. * With `trackBy`, only changing the `id` triggers element replacement.
trackBy

{@a ngSwitch} ### The _NgSwitch_ directives *NgSwitch* is like the JavaScript `switch` statement. It can display _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 seen in this example.
trackBy
`NgSwitch` is the controller directive. Bind it to an expression that returns the *switch value*. The `emotion` value in this example is a string, but 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. It changes the behavior of its companion directives. It doesn't touch the DOM directly. **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. * `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 "emotional hero" components defined in the `hero-switch.components.ts` file. Each component has a `hero` [input property](guide/template-syntax#inputs-outputs "Input property") which is bound to the `currentHero` 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 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 be a reference to an Angular component or directive or a web component. Use the hash symbol (#) to declare a reference variable. The `#phone` declares a `phone` variable on an `` element. You can refer to a template reference variable _anywhere_ in the template. The `phone` variable declared on this `` is consumed in a `