2019-12-02 15:47:19 -05:00
# Template syntax
2017-03-30 15:04:18 -04:00
2017-02-22 13:09:39 -05:00
< style >
2017-03-31 19:57:13 -04:00
h4 {font-size: 17px !important; text-transform: none !important;}
.syntax { font-family: Consolas, 'Lucida Sans', Courier, sans-serif; color: black; font-size: 85%; }
h4 .syntax { font-size: 100%; }
2017-02-22 13:09:39 -05:00
< / style >
2019-08-19 17:37:36 -04:00
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.
2017-02-22 13:09:39 -05:00
2017-04-26 08:11:02 -04:00
You may be familiar with the component/template duality from your experience with model-view-controller (MVC) or model-view-viewmodel (MVVM).
2017-02-22 13:09:39 -05:00
In Angular, the component plays the part of the controller/viewmodel, and the template represents the view.
2017-07-10 05:01:54 -04:00
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.
2017-06-09 04:05:16 -04:00
Many code snippets illustrate the points and concepts, all of them available
in the < live-example title = "Template Syntax Live Code" > < / live-example > .
2017-02-22 13:09:39 -05:00
{@a html}
## HTML in templates
2017-03-11 08:44:25 -05:00
HTML is the language of the Angular template.
2017-04-26 08:11:02 -04:00
Almost all HTML syntax is valid template syntax.
The `<script>` element is a notable exception;
2017-02-22 13:09:39 -05:00
it is forbidden, eliminating the risk of script injection attacks.
In practice, `<script>` is ignored and a warning appears in the browser console.
2017-03-11 10:36:40 -05:00
See the [Security ](guide/security ) page for details.
2017-02-22 13:09:39 -05:00
2017-04-26 08:11:02 -04:00
Some legal HTML doesn't make much sense in a template.
The `<html>` , `<body>` , and `<base>` elements have no useful role.
2017-02-22 13:09:39 -05:00
Pretty much everything else is fair game.
2017-04-26 08:11:02 -04:00
You can extend the HTML vocabulary of your templates with components and directives that appear as new elements and attributes.
2017-02-22 13:09:39 -05:00
In the following sections, you'll learn how to get and set DOM (Document Object Model) values dynamically through data binding.
Begin with the first form of data binding— interpolation— to see how much richer template HTML can be.
2017-03-30 15:04:18 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a interpolation}
2017-03-31 19:57:13 -04:00
2018-07-19 15:20:27 -04:00
## Interpolation and Template Expressions
2017-03-11 08:44:25 -05:00
2018-07-19 15:20:27 -04:00
Interpolation allows you to incorporate calculated strings into the text
between HTML element tags and within attribute assignments. Template
expressions are what you use to calculate those strings.
2017-02-22 13:09:39 -05:00
2018-07-19 15:20:27 -04:00
The interpolation < live-example > < / live-example > demonstrates all of
the syntax and code snippets described in this section.
### Interpolation `{{...}}`
Interpolation refers to embedding expressions into marked up text.
By default, interpolation uses as its delimiter the double curly braces, `{{` and `}}` .
In the following snippet, `{{ currentCustomer }}` is an example of interpolation.
2019-07-20 13:40:17 -04:00
< code-example path = "interpolation/src/app/app.component.html" region = "interpolation-example1" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-07-19 15:20:27 -04:00
The text between the braces is often the name of a component
property. Angular replaces that name with the
string value of the corresponding component property.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "interpolation/src/app/app.component.html" region = "component-property" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-07-19 15:20:27 -04:00
In the example above, Angular evaluates the `title` and `itemImageUrl` properties
and fills in the blanks, first displaying some title text and then an image.
2017-02-22 13:09:39 -05:00
2018-07-19 15:20:27 -04:00
More generally, the text between the braces is a **template expression**
that Angular first **evaluates** and then **converts to a string** .
The following interpolation illustrates the point by adding two numbers:
2017-03-11 08:44:25 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "interpolation/src/app/app.component.html" region = "convert-string" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-07-19 15:20:27 -04:00
The expression can invoke methods of the host component such as `getVal()` in
the following example:
2017-03-11 08:44:25 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "interpolation/src/app/app.component.html" region = "invoke-method" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2017-03-11 08:44:25 -05:00
Angular evaluates all expressions in double curly braces,
converts the expression results to strings, and links them with neighboring literal strings. Finally,
2017-02-22 13:09:39 -05:00
it assigns this composite interpolated result to an **element or directive property** .
You appear to be inserting the result between element tags and assigning it to attributes.
2019-08-19 17:37:36 -04:00
However, interpolation is a special syntax that Angular converts into a *property binding* .
2017-05-08 23:47:34 -04:00
2018-07-19 15:20:27 -04:00
< div class = "alert is-helpful" >
2017-09-27 16:45:25 -04:00
2018-07-19 15:20:27 -04:00
If you'd like to use something other than `{{` and `}}` , you can
configure the interpolation delimiter via the
[interpolation ](api/core/Component#interpolation )
option in the `Component` metadata.
2017-02-22 13:09:39 -05:00
2018-07-19 15:20:27 -04:00
< / div >
2017-03-31 19:57:13 -04:00
2018-07-19 15:20:27 -04:00
### Template expressions
2017-03-11 08:44:25 -05:00
2018-07-19 15:20:27 -04:00
A template **expression** produces a value and appears within the double
curly braces, `{{ }}` .
2017-02-22 13:09:39 -05:00
Angular executes the expression and assigns it to a property of a binding target;
2018-07-19 15:20:27 -04:00
the target could be an HTML element, a component, or a directive.
2017-02-22 13:09:39 -05:00
The interpolation braces in `{{1 + 1}}` surround the template expression `1 + 1` .
2018-07-19 15:20:27 -04:00
In the property binding,
2017-02-22 13:09:39 -05:00
a template expression appears in quotes to the right of the `=` symbol as in `[property]="expression"` .
2018-07-19 15:20:27 -04:00
In terms of syntax, template expressions are similar to JavaScript.
Many JavaScript expressions are legal template expressions, with a few exceptions.
2017-02-22 13:09:39 -05:00
2018-07-19 15:20:27 -04:00
You can't use JavaScript expressions that have or promote side effects,
2017-02-22 13:09:39 -05:00
including:
2018-07-19 15:20:27 -04:00
* Assignments (`=`, `+=` , `-=` , `...` )
* Operators such as `new` , `typeof` , `instanceof` , etc.
* Chaining expressions with < code > ;</ code > or < code > ,</ code >
* The increment and decrement operators `++` and `--`
* Some of the ES2015+ operators
2017-03-31 19:57:13 -04:00
2017-03-31 07:23:16 -04:00
Other notable differences from JavaScript syntax include:
2017-02-22 13:09:39 -05:00
2018-07-19 15:20:27 -04:00
* No support for the bitwise operators such as `|` and `&`
2019-08-19 17:37:36 -04:00
* New [template expression operators ](guide/template-syntax#expression-operators ), such as `|` , `?.` and `!`
2017-03-31 19:57:13 -04:00
2017-03-11 08:44:25 -05:00
### Expression context
2017-02-22 13:09:39 -05:00
The *expression context* is typically the _component_ instance.
2018-07-19 15:20:27 -04:00
In the following snippets, the `recommended` within double curly braces and the
`itemImageUrl2` in quotes refer to properties of the `AppComponent` .
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "interpolation/src/app/app.component.html" region = "component-context" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
An expression may also refer to properties of the _template's_ context
2018-07-19 15:20:27 -04:00
such as a template input variable,
<!-- link to built - in - directives#template - input - variables -->
`let customer` , or a template reference variable, `#customerInput` .
<!-- link to guide/template - ref - variables -->
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "interpolation/src/app/app.component.html" region = "template-input-variable" header = "src/app/app.component.html (template input variable)" > < / code-example >
2018-07-19 15:20:27 -04:00
2019-07-20 13:40:17 -04:00
< code-example path = "interpolation/src/app/app.component.html" region = "template-reference-variable" header = "src/app/app.component.html (template reference variable)" > < / code-example >
2017-02-22 13:09:39 -05:00
2017-03-11 08:44:25 -05:00
The context for terms in an expression is a blend of the _template variables_ ,
2017-02-22 13:09:39 -05:00
the directive's _context_ object (if it has one), and the component's _members_ .
If you reference a name that belongs to more than one of these namespaces,
2017-03-27 11:08:53 -04:00
the template variable name takes precedence, followed by a name in the directive's _context_ ,
2017-02-22 13:09:39 -05:00
and, lastly, the component's member names.
2018-07-19 15:20:27 -04:00
The previous example presents such a name collision. The component has a `customer`
property and the `*ngFor` defines a `customer` template variable.
< div class = "alert is-helpful" >
The `customer` in `{{customer.name}}`
2017-03-11 08:44:25 -05:00
refers to the template input variable, not the component's property.
Template expressions cannot refer to anything in
2018-07-19 15:20:27 -04:00
the global namespace, except `undefined` . They can't refer to
`window` or `document` . Additionally, they
can't call `console.log()` or `Math.max()` and they are restricted to referencing
2017-03-11 08:44:25 -05:00
members of the expression context.
2017-05-08 23:47:34 -04:00
2018-07-19 15:20:27 -04:00
< / div >
2017-03-31 19:57:13 -04:00
2017-02-22 13:09:39 -05:00
### Expression guidelines
2017-03-11 08:44:25 -05:00
2018-07-19 15:20:27 -04:00
When using template expressions follow these guidelines:
2017-02-22 13:09:39 -05:00
2017-03-11 10:36:40 -05:00
* [Simplicity ](guide/template-syntax#simplicity )
2019-08-19 17:37:36 -04:00
* [Quick execution ](guide/template-syntax#quick-execution )
* [No visible side effects ](guide/template-syntax#no-visible-side-effects )
#### Simplicity
Although it's possible to write complex template expressions, it's a better
practice to avoid them.
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
A property name or method call should be the norm, but an occasional Boolean negation, `!` , is OK.
Otherwise, confine application and business logic to the component,
where it is easier to develop and test.
#### Quick execution
Angular executes template expressions after every change detection cycle.
Change detection cycles are triggered by many asynchronous activities such as
promise resolutions, HTTP results, timer events, key presses and mouse moves.
Expressions should finish quickly or the user experience may drag, especially on slower devices.
Consider caching values when their computation is expensive.
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
#### No visible side effects
2017-02-22 13:09:39 -05:00
A template expression should not change any application state other than the value of the
target property.
This rule is essential to Angular's "unidirectional data flow" policy.
You should never worry that reading a component value might change some other displayed value.
The view should be stable throughout a single rendering pass.
2018-07-19 15:20:27 -04:00
An [idempotent ](https://en.wikipedia.org/wiki/Idempotence ) expression is ideal because
it is free of side effects and improves Angular's change detection performance.
In Angular terms, an idempotent expression always returns
2019-08-19 17:37:36 -04:00
*exactly the same thing* until one of its dependent values changes.
2017-02-22 13:09:39 -05:00
2018-07-19 15:20:27 -04:00
Dependent values should not change during a single turn of the event loop.
If an idempotent expression returns a string or a number, it returns the same string or number when called twice in a row. If the expression returns an object, including an `array` , it returns the same object *reference* when called twice in a row.
2017-02-22 13:09:39 -05:00
2018-07-19 15:20:27 -04:00
< div class = "alert is-helpful" >
2017-03-11 08:44:25 -05:00
2019-08-19 17:37:36 -04:00
There is one exception to this behavior that applies to `*ngFor` . `*ngFor` has `trackBy` functionality that can deal with referential inequality of objects when iterating over them. See [*ngFor with `trackBy` ](guide/template-syntax#ngfor-with-trackby ) for details.
2017-02-22 13:09:39 -05:00
2018-07-19 15:20:27 -04:00
< / div >
2017-03-11 08:44:25 -05:00
2018-07-19 15:20:27 -04:00
<!-- end of Interpolation doc -->
2017-03-30 15:04:18 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a template-statements}
2017-03-31 19:57:13 -04:00
2017-02-22 13:09:39 -05:00
## Template statements
A template **statement** responds to an **event** raised by a binding target
such as an element, component, or directive.
2017-03-11 10:36:40 -05:00
You'll see template statements in the [event binding ](guide/template-syntax#event-binding ) section,
2017-02-22 13:09:39 -05:00
appearing in quotes to the right of the `=` symbol as in `(event)="statement"` .
2019-07-20 13:40:17 -04:00
< code-example path = "template-syntax/src/app/app.component.html" region = "context-component-statement" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
A template statement *has a side effect* .
That's the whole point of an event.
It's how you update application state from user action.
Responding to events is the other side of Angular's "unidirectional data flow".
You're free to change anything, anywhere, during this turn of the event loop.
2017-03-31 07:23:16 -04:00
Like template expressions, template *statements* use a language that looks like JavaScript.
2017-03-11 08:44:25 -05:00
The template statement parser differs from the template expression parser and
specifically supports both basic assignment (`=`) and chaining expressions
2017-03-31 07:23:16 -04:00
(with < code > ;< / code > or < code > ,< / code > ).
2017-02-22 13:09:39 -05:00
2017-03-31 07:23:16 -04:00
However, certain JavaScript syntax is not allowed:
2017-03-11 08:44:25 -05:00
2017-03-31 07:23:16 -04:00
* < code > new</ code >
2017-02-22 13:09:39 -05:00
* increment and decrement operators, `++` and `--`
* operator assignment, such as `+=` and `-=`
* the bitwise operators `|` and `&`
2017-03-11 10:36:40 -05:00
* the [template expression operators ](guide/template-syntax#expression-operators )
2017-03-11 08:44:25 -05:00
2017-02-22 13:09:39 -05:00
### Statement context
As with expressions, statements can refer only to what's in the statement context
such as an event handling method of the component instance.
2017-03-11 08:44:25 -05:00
The *statement context* is typically the component instance.
2017-02-22 13:09:39 -05:00
The *deleteHero* in `(click)="deleteHero()"` is a method of the data-bound component.
2019-07-20 13:40:17 -04:00
< code-example path = "template-syntax/src/app/app.component.html" region = "context-component-statement" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
The statement context may also refer to properties of the template's own context.
In the following examples, the template `$event` object,
2017-03-11 10:36:40 -05:00
a [template input variable ](guide/template-syntax#template-input-variable ) (`let hero`),
and a [template reference variable ](guide/template-syntax#ref-vars ) (`#heroForm`)
2017-02-22 13:09:39 -05:00
are passed to an event handling method of the component.
2019-07-20 13:40:17 -04:00
< code-example path = "template-syntax/src/app/app.component.html" region = "context-var-statement" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
Template context names take precedence over component context names.
2017-03-11 08:44:25 -05:00
In `deleteHero(hero)` above, the `hero` is the template input variable,
not the component's `hero` property.
2019-08-19 17:37:36 -04:00
### Statement guidelines
2017-03-11 08:44:25 -05:00
Template statements cannot refer to anything in the global namespace. They
can't refer to `window` or `document` .
They can't call `console.log` or `Math.max` .
2017-02-22 13:09:39 -05:00
As with expressions, avoid writing complex template statements.
A method call or simple property assignment should be the norm.
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a binding-syntax}
2017-03-31 19:57:13 -04:00
2018-07-09 17:55:18 -04:00
## Binding syntax: an overview
2017-03-11 08:44:25 -05:00
2018-07-09 17:55:18 -04:00
Data-binding is a mechanism for coordinating what users see, specifically
with application data values.
2017-02-22 13:09:39 -05:00
While you could push values to and pull values from HTML,
2018-07-09 17:55:18 -04:00
the application is easier to write, read, and maintain if you turn these tasks over to a binding framework.
You simply declare bindings between binding sources, target HTML elements, and let the framework do the rest.
2017-02-22 13:09:39 -05:00
2018-07-09 17:55:18 -04:00
For a demonstration of the syntax and code snippets in this section, see the < live-example name = "binding-syntax" > binding syntax example< / live-example > .
2017-02-22 13:09:39 -05:00
2018-07-09 17:55:18 -04:00
Angular provides many kinds of data-binding. Binding types can be grouped into three categories distinguished by the direction of data flow:
* From the _source-to-view_
* From _view-to-source_
* Two-way sequence: _view-to-source-to-view_
2017-03-11 08:44:25 -05:00
2017-02-22 13:09:39 -05:00
< style >
td, th {vertical-align: top}
< / style >
< table width = "100%" >
< col width = "30%" >
< / col >
< col width = "50%" >
< / col >
< col width = "20%" >
< / col >
< tr >
< th >
2018-07-09 17:55:18 -04:00
Type
2017-02-22 13:09:39 -05:00
< / th >
< th >
Syntax
< / th >
< th >
2018-07-09 17:55:18 -04:00
Category
2017-02-22 13:09:39 -05:00
< / th >
< / tr >
< tr >
2018-07-09 17:55:18 -04:00
< td >
Interpolation< br >
Property< br >
Attribute< br >
Class< br >
Style
2017-02-22 13:09:39 -05:00
< / td >
< td >
< code-example >
2017-03-31 19:57:13 -04:00
{{expression}}
[target]="expression"
bind-target="expression"
2017-02-22 13:09:39 -05:00
< / code-example >
< / td >
2018-07-09 17:55:18 -04:00
2017-02-22 13:09:39 -05:00
< td >
2018-07-09 17:55:18 -04:00
One-way< br > from data source< br > to view target
2017-02-22 13:09:39 -05:00
< / td >
< tr >
< td >
2018-07-09 17:55:18 -04:00
Event
2017-02-22 13:09:39 -05:00
< / td >
< td >
< code-example >
2017-03-31 19:57:13 -04:00
(target)="statement"
on-target="statement"
2017-02-22 13:09:39 -05:00
< / code-example >
< / td >
2018-07-09 17:55:18 -04:00
2017-02-22 13:09:39 -05:00
< td >
2018-07-09 17:55:18 -04:00
One-way< br > from view target< br > to data source
2017-02-22 13:09:39 -05:00
< / td >
< / tr >
< tr >
< td >
Two-way
< / td >
< td >
< code-example >
2017-03-31 19:57:13 -04:00
[(target)]="expression"
bindon-target="expression"
2017-02-22 13:09:39 -05:00
< / code-example >
< / td >
< td >
Two-way
< / td >
< / tr >
< / tr >
< / table >
2018-07-09 17:55:18 -04:00
Binding types other than interpolation have a **target name** to the left of the equal sign, either surrounded by punctuation, `[]` or `()` ,
or preceded by a prefix: `bind-` , `on-` , `bindon-` .
2017-02-22 13:09:39 -05:00
2018-07-09 17:55:18 -04:00
The *target* of a binding is the property or event inside the binding punctuation: `[]` , `()` or `[()]` .
2017-02-22 13:09:39 -05:00
2018-07-09 17:55:18 -04:00
Every public member of a **source** directive is automatically available for binding.
You don't have to do anything special to access a directive member in a template expression or statement.
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
### Data-binding and HTML
2017-02-22 13:09:39 -05:00
In the normal course of HTML development, you create a visual structure with HTML elements, and
you modify those elements by setting element attributes with string constants.
2018-07-09 17:55:18 -04:00
```html
< div class = "special" > Plain old HTML< / div >
< img src = "images/item.png" >
< button disabled > Save< / button >
```
With data-binding, you can control things like the state of a button:
2019-07-20 13:40:17 -04:00
< code-example path = "binding-syntax/src/app/app.component.html" region = "disabled-button" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-07-09 17:55:18 -04:00
Notice that the binding is to the `disabled` property of the button's DOM element,
**not** the attribute. This applies to data-binding in general. Data-binding works with *properties* of DOM elements, components, and directives, not HTML *attributes* .
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
### HTML attribute vs. DOM property
2017-02-22 13:09:39 -05:00
2018-07-09 17:55:18 -04:00
The distinction between an HTML attribute and a DOM property is key to understanding
2019-08-19 17:37:36 -04:00
how Angular binding works. **Attributes are defined by HTML. Properties are accessed from DOM (Document Object Model) nodes.**
2017-02-22 13:09:39 -05:00
2018-07-09 17:55:18 -04:00
* A few HTML attributes have 1:1 mapping to properties; for example, `id` .
2017-02-22 13:09:39 -05:00
2018-07-09 17:55:18 -04:00
* Some HTML attributes don't have corresponding properties; for example, `aria-*` .
2017-02-22 13:09:39 -05:00
2018-07-09 17:55:18 -04:00
* Some DOM properties don't have corresponding attributes; for example, `textContent` .
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
It is important to remember that *HTML attribute* and the *DOM property* are different things, even when they have the same name.
In Angular, the only role of HTML attributes is to initialize element and directive state.
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
**Template binding works with *properties* and *events* , not *attributes* .**
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
When you write a data-binding, you're dealing exclusively with the *DOM properties* and *events* of the target object.
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
< div class = "alert is-helpful" >
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
This general rule can help you build a mental model of attributes and DOM properties:
**Attributes initialize DOM properties and then they are done.
Property values can change; attribute values can't.**
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
There is one exception to this rule.
Attributes can be changed by `setAttribute()` , which re-initializes corresponding DOM properties.
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
< / div >
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
For more information, see the [MDN Interfaces documentation ](https://developer.mozilla.org/en-US/docs/Web/API#Interfaces ) which has API docs for all the standard DOM elements and their properties.
Comparing the [`<td>` attributes ](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td ) attributes to the [`<td>` properties ](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement ) provides a helpful example for differentiation.
In particular, you can navigate from the attributes page to the properties via "DOM interface" link, and navigate the inheritance hierarchy up to `HTMLTableCellElement` .
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
#### Example 1: an `<input>`
2017-02-22 13:09:39 -05:00
2018-07-09 17:55:18 -04:00
When the browser renders `<input type="text" value="Sarah">` , it creates a
corresponding DOM node with a `value` property initialized to "Sarah".
2017-02-22 13:09:39 -05:00
2018-07-09 17:55:18 -04:00
```html
< input type = "text" value = "Sarah" >
```
When the user enters "Sally" into the `<input>` , the DOM element `value` *property* becomes "Sally".
However, if you look at the HTML attribute `value` using `input.getAttribute('value')` , you can see that the *attribute* remains unchanged— it returns "Sarah".
2017-02-22 13:09:39 -05:00
The HTML attribute `value` specifies the *initial* value; the DOM `value` property is the *current* value.
2018-07-09 17:55:18 -04:00
To see attributes versus DOM properties in a functioning app, see the < live-example name = "binding-syntax" > < / live-example > especially for binding syntax.
2019-08-19 17:37:36 -04:00
#### Example 2: a disabled button
2018-07-09 17:55:18 -04:00
The `disabled` attribute is another example. A button's `disabled`
*property* is `false` by default so the button is enabled.
When you add the `disabled` *attribute* , its presence alone
initializes the button's `disabled` *property* to `true`
2017-02-22 13:09:39 -05:00
so the button is disabled.
2018-07-09 17:55:18 -04:00
```html
< button disabled > Test Button< / button >
```
2019-08-19 17:37:36 -04:00
Adding and removing the `disabled` *attribute* disables and enables the button.
2018-07-09 17:55:18 -04:00
However, the value of the *attribute* is irrelevant,
2017-02-22 13:09:39 -05:00
which is why you cannot enable a button by writing `<button disabled="false">Still Disabled</button>` .
2018-07-09 17:55:18 -04:00
To control the state of the button, set the `disabled` *property* ,
2017-02-22 13:09:39 -05:00
2018-07-09 17:55:18 -04:00
< div class = "alert is-helpful" >
2019-08-19 17:37:36 -04:00
Though you could technically set the `[attr.disabled]` attribute binding, the values are different in that the property binding requires to a boolean value, while its corresponding attribute binding relies on whether the value is `null` or not. Consider the following:
2018-07-09 17:55:18 -04:00
```html
< input [ disabled ] = " condition ? true : false " >
< input [ attr . disabled ] = " condition ? ' disabled ' : null " >
```
Generally, use property binding over attribute binding as it is more intuitive (being a boolean value), has a shorter syntax, and is more performant.
2017-03-27 11:08:53 -04:00
2017-04-10 11:51:13 -04:00
< / div >
2017-03-27 11:08:53 -04:00
2017-02-22 13:09:39 -05:00
2018-07-09 17:55:18 -04:00
To see the `disabled` button example in a functioning app, see the < live-example name = "binding-syntax" ></ live-example > especially for binding syntax. This example shows you how to toggle the disabled property from the component.
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
## Binding types and targets
2017-03-11 08:44:25 -05:00
2018-07-09 17:55:18 -04:00
The **target of a data-binding** is something in the DOM.
2019-08-19 17:37:36 -04:00
Depending on the binding type, the target can be a property (element, component, or directive),
an event (element, component, or directive), or sometimes an attribute name.
The following table summarizes the targets for the different binding types.
2017-02-22 13:09:39 -05:00
< style >
td, th {vertical-align: top}
< / style >
< table width = "100%" >
< col width = "10%" >
< / col >
< col width = "15%" >
< / col >
< col width = "75%" >
< / col >
< tr >
< th >
Type
< / th >
< th >
Target
< / th >
< th >
Examples
< / th >
< / tr >
< tr >
< td >
Property
< / td >
< td >
2017-03-31 19:57:13 -04:00
Element property< br >
Component property< br >
Directive property
2017-02-22 13:09:39 -05:00
< / td >
< td >
2018-07-09 17:55:18 -04:00
< code > src< / code > , < code > hero< / code > , and < code > ngClass< / code > in the following:
2019-07-20 13:40:17 -04:00
< code-example path = "template-syntax/src/app/app.component.html" region = "property-binding-syntax-1" > < / code-example >
2018-07-09 17:55:18 -04:00
<!-- For more information, see [Property Binding ](guide/property-binding ). -->
2017-02-22 13:09:39 -05:00
< / td >
< / tr >
< tr >
< td >
Event
< / td >
< td >
2017-03-31 19:57:13 -04:00
Element event< br >
Component event< br >
Directive event
2017-02-22 13:09:39 -05:00
< / td >
< td >
2018-07-09 17:55:18 -04:00
< code > click< / code > , < code > deleteRequest< / code > , and < code > myClick< / code > in the following:
2019-07-20 13:40:17 -04:00
< code-example path = "template-syntax/src/app/app.component.html" region = "event-binding-syntax-1" > < / code-example >
2018-07-09 17:55:18 -04:00
<!-- KW - - Why don't these links work in the table? -->
<!-- <div>For more information, see [Event Binding ](guide/event-binding ).</div> -->
2017-02-22 13:09:39 -05:00
< / td >
< / tr >
< tr >
< td >
Two-way
< / td >
< td >
Event and property
< / td >
< td >
2019-07-20 13:40:17 -04:00
< code-example path = "template-syntax/src/app/app.component.html" region = "2-way-binding-syntax-1" > < / code-example >
2017-02-22 13:09:39 -05:00
< / td >
< / tr >
< tr >
< td >
Attribute
< / td >
< td >
2017-03-31 19:57:13 -04:00
Attribute
(the exception)
2017-02-22 13:09:39 -05:00
< / td >
< td >
2019-07-20 13:40:17 -04:00
< code-example path = "template-syntax/src/app/app.component.html" region = "attribute-binding-syntax-1" > < / code-example >
2017-02-22 13:09:39 -05:00
< / td >
< / tr >
< tr >
< td >
Class
< / td >
< td >
< code > class< / code > property
< / td >
< td >
2019-07-20 13:40:17 -04:00
< code-example path = "template-syntax/src/app/app.component.html" region = "class-binding-syntax-1" > < / code-example >
2017-02-22 13:09:39 -05:00
< / td >
< / tr >
< tr >
< td >
Style
< / td >
< td >
< code > style< / code > property
< / td >
< td >
2019-07-20 13:40:17 -04:00
< code-example path = "template-syntax/src/app/app.component.html" region = "style-binding-syntax-1" > < / code-example >
2017-02-22 13:09:39 -05:00
< / td >
< / tr >
< / table >
2018-07-09 17:55:18 -04:00
<!-- end of binding syntax -->
2017-03-30 15:04:18 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a property-binding}
2017-03-31 19:57:13 -04:00
2018-08-28 12:46:59 -04:00
## Property binding `[property]`
2017-03-11 08:44:25 -05:00
2018-08-28 12:46:59 -04:00
Use property binding to _set_ properties of target elements or
directive `@Input()` decorators. For an example
demonstrating all of the points in this section, see the
< live-example name = "property-binding" > property binding example< / live-example > .
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
### One-way in
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
Property binding flows a value in one direction,
from a component's property into a target element property.
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
You can't use property
binding to read or pull values out of target elements. Similarly, you cannot use
property binding to call a method on the target element.
If the element raises events, you can listen to them with an [event binding ](guide/template-syntax#event-binding ).
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
If you must read a target element property or call one of its methods,
see the API reference for [ViewChild ](api/core/ViewChild ) and
[ContentChild ](api/core/ContentChild ).
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
### Examples
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
The most common property binding sets an element property to a component
property value. An example is
binding the `src` property of an image element to a component's `itemImageUrl` property:
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "property-binding" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
Here's an example of binding to the `colSpan` property. Notice that it's not `colspan` ,
which is the attribute, spelled with a lowercase `s` .
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "colSpan" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2019-09-22 03:35:32 -04:00
For more details, see the [MDN HTMLTableCellElement ](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement ) documentation.
2017-03-11 08:44:25 -05:00
2018-08-28 12:46:59 -04:00
<!-- Add link when Attribute Binding updates are merged:
For more about `colSpan` and `colspan` , see (Attribute Binding)[guide/template-syntax]. -->
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
Another example is disabling a button when the component says that it `isUnchanged` :
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "disabled-button" header = "src/app/app.component.html" > < / code-example >
2017-03-27 11:08:53 -04:00
2018-08-28 12:46:59 -04:00
Another is setting a property of a directive:
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "class-binding" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
Yet another is setting the model property of a custom component— a great way
for parent and child components to communicate:
2017-03-27 11:08:53 -04:00
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "model-property-binding" header = "src/app/app.component.html" > < / code-example >
2017-03-27 11:08:53 -04:00
2019-08-19 17:37:36 -04:00
### Binding targets
2017-03-11 08:44:25 -05:00
2019-08-19 17:37:36 -04:00
An element property between enclosing square brackets identifies the target property.
2017-03-11 08:44:25 -05:00
The target property in the following code is the image element's `src` property.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "property-binding" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
There's also the `bind-` prefix alternative:
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "bind-prefix" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
In most cases, the target name is the name of a property, even
when it appears to be the name of an attribute.
So in this case, `src` is the name of the `<img>` element property.
2017-02-22 13:09:39 -05:00
Element properties may be the more common targets,
but Angular looks first to see if the name is a property of a known directive,
as it is in the following example:
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "class-binding" header = "src/app/app.component.html" > < / code-example >
2017-03-27 11:08:53 -04:00
2018-08-28 12:46:59 -04:00
Technically, Angular is matching the name to a directive `@Input()` ,
one of the property names listed in the directive's `inputs` array
or a property decorated with `@Input()` .
Such inputs map to the directive's own properties.
If the name fails to match a property of a known directive or element, Angular reports an “unknown directive” error.
2018-07-19 18:00:08 -04:00
< div class = "alert is-helpful" >
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
Though the target name is usually the name of a property,
there is an automatic attribute-to-property mapping in Angular for
several common attributes. These include `class` /`className`, `innerHtml` /`innerHTML`, and
`tabindex` /`tabIndex`.
2017-03-27 11:08:53 -04:00
2017-04-10 11:51:13 -04:00
< / div >
2017-03-27 11:08:53 -04:00
2017-02-22 13:09:39 -05:00
### Avoid side effects
2017-03-11 08:44:25 -05:00
2018-08-28 12:46:59 -04:00
Evaluation of a template expression should have no visible side effects.
The expression language itself, or the way you write template expressions,
helps to a certain extent;
you can't assign a value to anything in a property binding expression
nor use the increment and decrement operators.
For example, you could have an expression that invoked a property or method that had
side effects. The expression could call something like `getFoo()` where only you
know what `getFoo()` does. If `getFoo()` changes something
and you happen to be binding to that something,
Angular may or may not display the changed value. Angular may detect the
change and throw a warning error.
As a best practice, stick to properties and to methods that return
values and avoid side effects.
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
### Return the proper type
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
The template expression should evaluate to the type of value
that the target property expects.
Return a string if the target property expects a string, a number if it
expects a number, an object if it expects an object, and so on.
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
In the following example, the `childItem` property of the `ItemDetailComponent` expects a string, which is exactly what you're sending in the property binding:
2017-03-11 08:44:25 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "model-property-binding" header = "src/app/app.component.html" > < / code-example >
2018-08-28 12:46:59 -04:00
You can confirm this by looking in the `ItemDetailComponent` where the `@Input` type is set to a string:
2019-09-09 03:21:31 -04:00
< code-example path = "property-binding/src/app/item-detail/item-detail.component.ts" region = "input-type" header = "src/app/item-detail/item-detail.component.ts (setting the @Input () type)" ></ code-example >
2018-08-28 12:46:59 -04:00
As you can see here, the `parentItem` in `AppComponent` is a string, which the `ItemDetailComponent` expects:
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.ts" region = "parent-data-type" header = "src/app/app.component.ts" > < / code-example >
2018-08-28 12:46:59 -04:00
#### Passing in an object
The previous simple example showed passing in a string. To pass in an object,
the syntax and thinking are the same.
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
In this scenario, `ListItemComponent` is nested within `AppComponent` and the `item` property expects an object.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "pass-object" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
The `item` property is declared in the `ListItemComponent` with a type of `Item` and decorated with `@Input()` :
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/list-item/list-item.component.ts" region = "item-input" header = "src/app/list-item.component.ts" > < / code-example >
2018-08-28 12:46:59 -04:00
In this sample app, an `Item` is an object that has two properties; an `id` and a `name` .
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/item.ts" region = "item-class" header = "src/app/item.ts" > < / code-example >
2018-08-28 12:46:59 -04:00
While a list of items exists in another file, `mock-items.ts` , you can
specify a different item in `app.component.ts` so that the new item will render:
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.ts" region = "pass-object" header = "src/app.component.ts" > < / code-example >
2018-08-28 12:46:59 -04:00
You just have to make sure, in this case, that you're supplying an object because that's the type of `item` and is what the nested component, `ListItemComponent` , expects.
In this example, `AppComponent` specifies a different `item` object
(`currentItem`) and passes it to the nested `ListItemComponent` . `ListItemComponent` was able to use `currentItem` because it matches what an `Item` object is according to `item.ts` . The `item.ts` file is where
`ListItemComponent` gets its definition of an `item` .
2017-02-22 13:09:39 -05:00
### Remember the brackets
2017-03-11 08:44:25 -05:00
2018-08-28 12:46:59 -04:00
The brackets, `[]` , tell Angular to evaluate the template expression.
2017-03-11 08:44:25 -05:00
If you omit the brackets, Angular treats the string as a constant
2018-08-28 12:46:59 -04:00
and *initializes the target property* with that string:
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "no-evaluation" header = "src/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
Omitting the brackets will render the string
`parentItem` , not the value of `parentItem` .
2017-03-31 19:57:13 -04:00
2017-02-22 13:09:39 -05:00
### One-time string initialization
2017-03-11 08:44:25 -05:00
2017-02-22 13:09:39 -05:00
You *should* omit the brackets when all of the following are true:
2017-03-31 19:57:13 -04:00
2017-02-22 13:09:39 -05:00
* The target property accepts a string value.
2018-08-28 12:46:59 -04:00
* The string is a fixed value that you can put directly into the template.
2017-02-22 13:09:39 -05:00
* This initial value never changes.
You routinely initialize attributes this way in standard HTML, and it works
just as well for directive and component property initialization.
2018-08-28 12:46:59 -04:00
The following example initializes the `prefix` property of the `StringInitComponent` to a fixed string,
2017-02-22 13:09:39 -05:00
not a template expression. Angular sets it and forgets about it.
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "string-init" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
The `[item]` binding, on the other hand, remains a live binding to the component's `currentItem` property.
2017-04-30 16:10:32 -04:00
2018-08-28 12:46:59 -04:00
### Property binding vs. interpolation
2017-03-11 08:44:25 -05:00
You often have a choice between interpolation and property binding.
2017-02-22 13:09:39 -05:00
The following binding pairs do the same thing:
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "property-binding-interpolation" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
Interpolation is a convenient alternative to property binding in
many cases. When rendering data values as strings, there is no
technical reason to prefer one form to the other, though readability
tends to favor interpolation. However, *when setting an element
property to a non-string data value, you must use property binding*.
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
### Content security
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
Imagine the following malicious content.
2017-03-31 19:57:13 -04:00
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.ts" region = "malicious-content" header = "src/app/app.component.ts" > < / code-example >
2017-03-11 08:44:25 -05:00
2018-08-28 12:46:59 -04:00
In the component template, the content might be used with interpolation:
2017-02-22 13:09:39 -05:00
2019-10-17 11:05:19 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "malicious-interpolated" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-08-28 12:46:59 -04:00
Fortunately, Angular data binding is on alert for dangerous HTML. In the above case,
the HTML displays as is, and the Javascript does not execute. Angular **does not**
allow HTML with script tags to leak into the browser, neither with interpolation
2017-02-22 13:09:39 -05:00
nor property binding.
2018-08-28 12:46:59 -04:00
In the following example, however, Angular [sanitizes ](guide/security#sanitization-and-security-contexts )
the values before displaying them.
2017-03-11 08:44:25 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "property-binding/src/app/app.component.html" region = "malicious-content" header = "src/app/app.component.html" > < / code-example >
2017-05-09 18:53:32 -04:00
2018-08-28 12:46:59 -04:00
Interpolation handles the `<script>` tags differently than
property binding but both approaches render the
content harmlessly. The following is the browser output
of the `evilTitle` examples.
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
< code-example language = "bash" >
2018-08-28 12:46:59 -04:00
"Template < script > alert ( "evil never sleeps" ) < / script > Syntax" is the interpolated evil title.
"Template alert("evil never sleeps")Syntax" is the property bound evil title.
2019-08-19 17:37:36 -04:00
< / code-example >
2017-03-30 15:04:18 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a other-bindings}
2017-03-31 19:57:13 -04:00
2017-02-22 13:09:39 -05:00
## Attribute, class, and style bindings
2017-03-11 08:44:25 -05:00
2018-09-10 16:30:24 -04:00
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 < live-example name = "attribute-binding" > < / live-example > especially for this section.
2017-02-22 13:09:39 -05:00
### Attribute binding
2017-03-11 08:44:25 -05:00
2018-09-10 16:30:24 -04:00
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.
2017-03-11 08:44:25 -05:00
2018-09-10 16:30:24 -04:00
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.
2017-03-27 11:08:53 -04:00
2018-09-10 16:30:24 -04:00
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.
2017-03-27 11:08:53 -04:00
2018-09-10 16:30:24 -04:00
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` .
2017-03-27 11:08:53 -04:00
2018-09-10 16:30:24 -04:00
One of the primary use cases for attribute binding
is to set ARIA attributes, as in this example:
2019-07-20 13:40:17 -04:00
< code-example path = "attribute-binding/src/app/app.component.html" region = "attrib-binding-aria" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-09-10 16:30:24 -04:00
< div class = "alert is-helpful" >
2017-02-22 13:09:39 -05:00
2018-09-10 16:30:24 -04:00
#### `colspan` and `colSpan`
2017-02-22 13:09:39 -05:00
2018-09-10 16:30:24 -04:00
Notice the difference between the `colspan` attribute and the `colSpan` property.
If you wrote something like this:
2017-03-11 08:44:25 -05:00
2017-02-22 13:09:39 -05:00
< code-example language = "html" >
2017-03-31 19:57:13 -04:00
< tr> < td colspan="{{1 + 1}}"> Three-Four< /td> < /tr>
2017-02-22 13:09:39 -05:00
< / code-example >
2018-09-10 16:30:24 -04:00
You'd get this error:
2017-03-11 08:44:25 -05:00
2019-08-19 17:37:36 -04:00
< code-example language = "bash" >
2017-03-31 19:57:13 -04:00
Template parse errors:
Can't bind to 'colspan' since it isn't a known native property
2017-02-22 13:09:39 -05:00
< / code-example >
2018-09-10 16:30:24 -04:00
As the message says, the `<td>` 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.
2017-02-22 13:09:39 -05:00
2018-09-10 16:30:24 -04:00
Instead, you'd use property binding and write it like this:
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "attribute-binding/src/app/app.component.html" region = "colSpan" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-09-10 16:30:24 -04:00
< / div >
2017-02-22 13:09:39 -05:00
2017-03-30 15:04:18 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-03-31 19:57:13 -04:00
2017-02-22 13:09:39 -05:00
### Class binding
2018-09-10 16:30:24 -04:00
Add and remove CSS class names from an element's `class` attribute with
2017-02-22 13:09:39 -05:00
a **class binding** .
2020-01-29 20:31:09 -05:00
Here's how to set the attribute without a binding in plain HTML:
2018-09-10 16:30:24 -04:00
```html
<!-- standard class attribute setting -->
< div class = "item clearance special" > Item clearance special< / div >
```
Class binding syntax resembles property binding, but instead of an element property between brackets, start with the prefix `class` ,
2020-01-29 20:31:09 -05:00
optionally followed by a dot (`.`) and the name of a CSS class: `[class.class-name]` .
Angular adds the class when the template expression evaluates to truthy.
It removes the class when the expression is falsy.
Binding to a specific class is additive, so it won't overwrite other class bindings or static classes unless the class names are duplicated.
2017-02-22 13:09:39 -05:00
2020-01-29 20:31:09 -05:00
In the example below, the final class list for the `<div>` will be `"item clearance special"` if `isSpecial` is truthy, and only `"item clearance"` if it is falsy.
2018-09-10 16:30:24 -04:00
2020-01-29 20:31:09 -05:00
< code-example path = "attribute-binding/src/app/app.component.html" region = "add-class" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2020-01-29 20:31:09 -05:00
You can also use the alternative class binding syntax that replaces square brackets with the `bind-` keyword:
2017-02-22 13:09:39 -05:00
2020-01-29 20:31:09 -05:00
< code-example path = "attribute-binding/src/app/app.component.html" region = "bind-syntax" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2020-01-29 20:31:09 -05:00
If there are multiple classes you'd like to toggle, you can bind to the `[class]` property directly.
Binding to `[class]` is additive, so it shouldn't overwrite other class bindings or static classes unless the class names are duplicated*.
2017-02-22 13:09:39 -05:00
2020-01-29 20:31:09 -05:00
< code-example path = "attribute-binding/src/app/app.component.html" region = "direct-class-binding" header = "src/app/app.component.html" > < / code-example >
2017-03-11 08:44:25 -05:00
2020-01-29 20:31:09 -05:00
The expression attached to the `[class]` binding is most often a string list of class names like `"clearance special"` .
2017-03-27 11:08:53 -04:00
2020-01-29 20:31:09 -05:00
You can also format the expression as an object with class names as the keys and truthy/falsy expressions as the values, like `{clearance: true, special: false}` .
In this case, Angular will add a class only if its associated value is truthy.
It's important to note that with object format, the identity of the object must change for the class list to be updated.
Updating the property without changing object identity will have no effect.
2017-03-27 11:08:53 -04:00
2020-01-29 20:31:09 -05:00
*This is true for Angular version 9 and later. For Angular version 8, see < a href = "http://v8.angular.io/guide/template-syntax#class-binding" > v8.angular.io< / a >
2017-03-30 15:04:18 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-03-31 19:57:13 -04:00
2017-02-22 13:09:39 -05:00
### 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]` .
2019-07-20 13:40:17 -04:00
< code-example path = "attribute-binding/src/app/app.component.html" region = "style-binding" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2017-03-11 08:44:25 -05:00
Some style binding styles have a unit extension.
2019-10-26 10:35:03 -04:00
The following example conditionally sets the font size in “em” and “%” units.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "attribute-binding/src/app/app.component.html" region = "style-binding-condition" header = "src/app/app.component.html" > < / code-example >
2017-03-27 11:08:53 -04:00
2019-08-19 17:37:36 -04:00
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.
2017-03-27 11:08:53 -04:00
2018-07-19 18:00:08 -04:00
< div class = "alert is-helpful" >
2017-03-27 11:08:53 -04:00
2017-02-22 13:09:39 -05:00
Note that a _style property_ name can be written in either
2017-03-31 19:57:13 -04:00
[dash-case ](guide/glossary#dash-case ), as shown above, or
[camelCase ](guide/glossary#camelcase ), such as `fontSize` .
2017-03-27 11:08:53 -04:00
2017-04-10 11:51:13 -04:00
< / div >
2017-03-27 11:08:53 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a event-binding}
2017-03-31 19:57:13 -04:00
2018-09-10 16:30:24 -04:00
## Event binding `(event)`
2017-02-22 13:09:39 -05:00
2018-09-10 16:30:24 -04:00
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 < live-example name = "event-binding" > event binding example< / live-example > .
2017-02-22 13:09:39 -05:00
2018-09-10 16:30:24 -04:00
Angular event binding syntax consists of a **target event** name
2017-03-11 08:44:25 -05:00
within parentheses on the left of an equal sign, and a quoted
2018-09-10 16:30:24 -04:00
template statement on the right.
2017-03-11 08:44:25 -05:00
The following event binding listens for the button's click events, calling
2017-02-22 13:09:39 -05:00
the component's `onSave()` method whenever a click occurs:
2019-11-11 17:47:51 -05:00
< div class = "lightbox" >
< img src = 'generated/images/guide/template-syntax/syntax-diagram.svg' alt = "Syntax diagram" >
< / div >
2017-02-22 13:09:39 -05:00
### Target event
2017-03-11 08:44:25 -05:00
2018-09-10 16:30:24 -04:00
As above, the target is the button's click event.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "event-binding/src/app/app.component.html" region = "event-binding-1" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-09-10 16:30:24 -04:00
Alternatively, use the `on-` prefix, known as the canonical form:
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "event-binding/src/app/app.component.html" region = "event-binding-2" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
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:
2019-07-20 13:40:17 -04:00
< code-example path = "event-binding/src/app/app.component.html" region = "custom-directive" header = "src/app/app.component.html" > < / code-example >
2017-03-27 11:08:53 -04:00
2017-02-22 13:09:39 -05:00
If the name fails to match an element event or an output property of a known directive,
Angular reports an “unknown directive” error.
2018-09-10 16:30:24 -04:00
2017-02-22 13:09:39 -05:00
### *$event* and event handling statements
2017-03-11 08:44:25 -05:00
2017-02-22 13:09:39 -05:00
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.
2018-09-10 16:30:24 -04:00
The binding conveys information about the event. This information can include data values such as an event object, string, or number named `$event` .
2017-02-22 13:09:39 -05:00
2018-09-10 16:30:24 -04:00
The target event determines the shape of the `$event` object.
2017-02-22 13:09:39 -05:00
If the target event is a native DOM element event, then `$event` is a
2017-03-31 19:57:13 -04:00
[DOM event object ](https://developer.mozilla.org/en-US/docs/Web/Events ),
2017-02-22 13:09:39 -05:00
with properties such as `target` and `target.value` .
Consider this example:
2019-07-20 13:40:17 -04:00
< code-example path = "event-binding/src/app/app.component.html" region = "event-binding-3" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-09-10 16:30:24 -04:00
This code sets the `<input>` `value` property by binding to the `name` property.
To listen for changes to the value, the code binds to the `input`
event of the `<input>` element.
2017-03-11 08:44:25 -05:00
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` .
2017-02-22 13:09:39 -05:00
To update the `name` property, the changed text is retrieved by following the path `$event.target.value` .
2018-09-10 16:30:24 -04:00
If the event belongs to a directive— recall that components
are directives— `$event` has whatever shape the directive produces.
2017-02-22 13:09:39 -05:00
2018-09-10 16:30:24 -04:00
### Custom events with `EventEmitter`
2017-02-22 13:09:39 -05:00
2017-04-30 16:10:32 -04:00
Directives typically raise custom events with an Angular [EventEmitter ](api/core/EventEmitter ).
2017-02-22 13:09:39 -05:00
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.
2018-09-10 16:30:24 -04:00
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` :
2017-02-22 13:09:39 -05:00
2017-03-27 11:08:53 -04:00
2019-07-20 13:40:17 -04:00
< code-example path = "event-binding/src/app/item-detail/item-detail.component.html" header = "src/app/item-detail/item-detail.component.html (template)" region = "line-through" > < / code-example >
2017-03-27 11:08:53 -04:00
2019-07-20 13:40:17 -04:00
< code-example path = "event-binding/src/app/item-detail/item-detail.component.ts" header = "src/app/item-detail/item-detail.component.ts (deleteRequest)" region = "deleteRequest" > < / code-example >
2017-03-27 11:08:53 -04:00
2018-09-10 16:30:24 -04:00
2017-03-11 08:44:25 -05:00
The component defines a `deleteRequest` property that returns an `EventEmitter` .
When the user clicks *delete* , the component invokes the `delete()` method,
2018-09-10 16:30:24 -04:00
telling the `EventEmitter` to emit an `Item` object.
2017-02-22 13:09:39 -05:00
2018-09-10 16:30:24 -04:00
Now imagine a hosting parent component that binds to the `deleteRequest` event
of the `ItemDetailComponent` .
2017-03-27 11:08:53 -04:00
2019-07-20 13:40:17 -04:00
< code-example path = "event-binding/src/app/app.component.html" header = "src/app/app.component.html (event-binding-to-component)" region = "event-binding-to-component" > < / code-example >
2017-03-27 11:08:53 -04:00
2018-09-10 16:30:24 -04:00
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.
2017-02-22 13:09:39 -05:00
### Template statements have side effects
2017-03-11 08:44:25 -05:00
2018-09-10 16:30:24 -04:00
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.
2017-02-22 13:09:39 -05:00
2018-09-10 16:30:24 -04:00
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.
2017-05-08 23:47:34 -04:00
2017-03-30 15:04:18 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a two-way}
2017-03-31 19:57:13 -04:00
2018-10-03 15:49:05 -04:00
## Two-way binding `[(...)]`
2017-03-11 08:44:25 -05:00
2018-10-03 15:49:05 -04:00
Two-way binding gives your app a way to share data between a component class and
its template.
2017-02-22 13:09:39 -05:00
2018-10-03 15:49:05 -04:00
For a demonstration of the syntax and code snippets in this section, see the < live-example name = "two-way-binding" > two-way binding example< / live-example > .
2017-02-22 13:09:39 -05:00
2018-10-03 15:49:05 -04:00
### 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, `()` .
2017-02-22 13:09:39 -05:00
2017-04-10 11:51:13 -04:00
< div class = "callout is-important" >
2017-02-22 13:09:39 -05:00
< header >
[( )] = banana in a box
< / header >
Visualize a *banana in a box* to remember that the parentheses go _inside_ the brackets.
2017-04-10 11:51:13 -04:00
< / div >
2017-02-22 13:09:39 -05:00
2018-10-03 15:49:05 -04:00
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.
2017-02-22 13:09:39 -05:00
It has a `size` value property and a companion `sizeChange` event:
2019-07-20 13:40:17 -04:00
< code-example path = "two-way-binding/src/app/sizer/sizer.component.ts" header = "src/app/sizer.component.ts" > < / code-example >
2017-02-22 13:09:39 -05:00
2019-11-12 17:50:13 -05:00
< code-example path = "two-way-binding/src/app/sizer/sizer.component.html" header = "src/app/sizer.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
The initial `size` is an input value from a property binding.
2018-10-03 15:49:05 -04:00
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.
2017-02-22 13:09:39 -05:00
Here's an example in which the `AppComponent.fontSizePx` is two-way bound to the `SizerComponent` :
2017-03-27 11:08:53 -04:00
2019-07-20 13:40:17 -04:00
< code-example path = "two-way-binding/src/app/app.component.html" header = "src/app/app.component.html (two-way-1)" region = "two-way-1" > < / code-example >
2017-03-27 11:08:53 -04:00
2017-02-22 13:09:39 -05:00
The `AppComponent.fontSizePx` establishes the initial `SizerComponent.size` value.
2018-10-03 15:49:05 -04:00
2019-07-20 13:40:17 -04:00
< code-example path = "two-way-binding/src/app/app.component.ts" header = "src/app/app.component.ts" region = "font-size" > < / code-example >
2018-10-03 15:49:05 -04:00
2017-02-22 13:09:39 -05:00
Clicking the buttons updates the `AppComponent.fontSizePx` via the two-way binding.
2017-03-11 08:44:25 -05:00
The revised `AppComponent.fontSizePx` value flows through to the _style_ binding,
making the displayed text bigger or smaller.
2017-02-22 13:09:39 -05:00
The two-way binding syntax is really just syntactic sugar for a _property_ binding and an _event_ binding.
2018-10-03 15:49:05 -04:00
Angular desugars the `SizerComponent` binding into this:
2017-03-27 11:08:53 -04:00
2019-07-20 13:40:17 -04:00
< code-example path = "two-way-binding/src/app/app.component.html" header = "src/app/app.component.html (two-way-2)" region = "two-way-2" > < / code-example >
2017-03-27 11:08:53 -04:00
2017-02-22 13:09:39 -05:00
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.
2019-08-19 17:37:36 -04:00
### Two-way binding in forms
2017-02-22 13:09:39 -05:00
2018-10-03 15:49:05 -04:00
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 `<input>` and
`<select>` . However, no native HTML element follows the `x`
value and `xChange` event pattern.
2017-05-08 23:47:34 -04:00
2018-10-03 15:49:05 -04:00
For more on how to use two-way binding in forms, see
Angular [NgModel ](guide/template-syntax#ngModel ).
2017-03-30 15:04:18 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a directives}
2017-03-31 19:57:13 -04:00
2017-02-22 13:09:39 -05:00
## Built-in directives
2018-10-09 14:32:58 -04:00
Angular offers two kinds of built-in directives: attribute
directives and structural directives. This segment reviews some of the most common built-in directives,
classified as either [_attribute_ directives ](guide/template-syntax#attribute-directives ) or [_structural_ directives ](guide/template-syntax#structural-directives ) and has its own < live-example name = "built-in-directives" > built-in directives example</ live-example > .
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
For more detail, including how to build your own custom directives, see [Attribute Directives ](guide/attribute-directives ) and [Structural Directives ](guide/structural-directives ).
2017-02-22 13:09:39 -05:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a attribute-directives}
2017-03-31 19:57:13 -04:00
2018-10-09 14:32:58 -04:00
### Built-in attribute directives
2017-02-22 13:09:39 -05:00
Attribute directives listen to and modify the behavior of
2017-03-11 08:44:25 -05:00
other HTML elements, attributes, properties, and components.
2018-10-09 14:32:58 -04:00
You usually apply them to elements as if they were HTML attributes, hence the name.
2017-02-22 13:09:39 -05:00
2017-08-18 01:52:38 -04:00
Many NgModules such as the [`RouterModule` ](guide/router "Routing and Navigation" )
2017-03-31 19:57:13 -04:00
and the [`FormsModule` ](guide/forms "Forms" ) define their own attribute directives.
2018-10-09 14:32:58 -04:00
The most common attribute directives are as follows:
2017-09-27 16:45:25 -04:00
2018-10-09 14:32:58 -04:00
* [`NgClass` ](guide/template-syntax#ngClass )— adds and removes a set of CSS classes.
* [`NgStyle` ](guide/template-syntax#ngStyle )— adds and removes a set of HTML styles.
* [`NgModel` ](guide/template-syntax#ngModel )— adds two-way data binding to an HTML form element.
2017-03-30 15:04:18 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a ngClass}
2017-03-31 19:57:13 -04:00
2018-10-09 14:32:58 -04:00
### `NgClass`
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
Add or remove several CSS classes simultaneously with `ngClass` .
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "special-div" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
< div class = "alert is-helpful" >
To add or remove a *single* class, use [class binding ](guide/template-syntax#class-binding ) rather than `NgClass` .
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
< / div >
2017-03-31 19:57:13 -04:00
2018-10-09 14:32:58 -04:00
Consider a `setCurrentClasses()` component method that sets a component property,
`currentClasses` , with an object that adds or removes three classes based on the
`true` /`false` state of three other component properties. Each key of the object is a CSS class name; its value is `true` if the class should be added,
`false` if it should be removed.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.ts" region = "setClasses" header = "src/app/app.component.ts" > < / code-example >
2017-02-22 13:09:39 -05:00
2017-03-11 08:44:25 -05:00
Adding an `ngClass` property binding to `currentClasses` sets the element's classes accordingly:
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "NgClass-1" header = "src/app/app.component.html" > < / code-example >
2017-03-27 11:08:53 -04:00
2018-07-19 18:00:08 -04:00
< div class = "alert is-helpful" >
2017-03-27 11:08:53 -04:00
2018-10-09 14:32:58 -04:00
Remember that in this situation you'd call `setCurrentClasses()` ,
both initially and when the dependent properties change.
2017-03-27 11:08:53 -04:00
2017-04-10 11:51:13 -04:00
< / div >
2017-03-27 11:08:53 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a ngStyle}
2017-03-31 19:57:13 -04:00
2018-10-09 14:32:58 -04:00
### `NgStyle`
2017-03-11 08:44:25 -05:00
2018-10-09 14:32:58 -04:00
Use `NgStyle` to set many inline styles simultaneously and dynamically, based on the state of the component.
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
#### Without `NgStyle`
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
For context, consider setting a *single* style value with [style binding ](guide/template-syntax#style-binding ), without `NgStyle` .
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "without-ng-style" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
However, to set *many* inline styles at the same time, use the `NgStyle` directive.
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
The following is a `setCurrentStyles()` method that sets a component
property, `currentStyles` , with an object that defines three styles,
based on the state of three other component properties:
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.ts" region = "setStyles" header = "src/app/app.component.ts" > < / code-example >
2017-02-22 13:09:39 -05:00
Adding an `ngStyle` property binding to `currentStyles` sets the element's styles accordingly:
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "NgStyle-2" header = "src/app/app.component.html" > < / code-example >
2017-03-27 11:08:53 -04:00
2018-07-19 18:00:08 -04:00
< div class = "alert is-helpful" >
2017-03-27 11:08:53 -04:00
2018-10-09 14:32:58 -04:00
Remember to call `setCurrentStyles()` , both initially and when the dependent properties change.
2017-03-27 11:08:53 -04:00
2017-04-10 11:51:13 -04:00
< / div >
2017-03-27 11:08:53 -04:00
2017-03-30 15:04:18 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a ngModel}
2017-03-31 19:57:13 -04:00
2018-10-09 14:32:58 -04:00
### `[(ngModel)]`: Two-way binding
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
The `NgModel` directive allows you to display a data property and
update that property when the user makes changes. Here's an example:
2017-03-27 11:08:53 -04:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" header = "src/app/app.component.html (NgModel example)" region = "NgModel-1" > < / code-example >
2017-03-27 11:08:53 -04:00
2018-10-09 14:32:58 -04:00
#### Import `FormsModule` to use `ngModel`
2017-03-31 07:23:16 -04:00
Before using the `ngModel` directive in a two-way data binding,
2017-07-11 18:05:20 -04:00
you must import the `FormsModule` and add it to the NgModule's `imports` list.
2018-10-09 14:32:58 -04:00
Learn more about the `FormsModule` and `ngModel` in [Forms ](guide/forms#ngModel ).
2017-03-31 07:23:16 -04:00
2018-10-09 14:32:58 -04:00
Remember to import the `FormsModule` to make `[(ngModel)]` available as follows:
2017-03-31 07:23:16 -04:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.module.ts" header = "src/app/app.module.ts (FormsModule import)" region = "import-forms-module" > < / code-example >
2017-03-31 07:23:16 -04:00
2017-03-11 08:44:25 -05:00
2018-10-09 14:32:58 -04:00
You could achieve the same result with separate bindings to
the `<input>` element's `value` property and `input` event:
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "without-NgModel" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
To streamline the syntax, the `ngModel` directive hides the details behind its own `ngModel` input and `ngModelChange` output properties:
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "NgModelChange" header = "src/app/app.component.html" > < / code-example >
2017-03-27 11:08:53 -04:00
2017-02-22 13:09:39 -05:00
The `ngModel` data property sets the element's value property and the `ngModelChange` event property
listens for changes to the element's value.
2018-10-09 14:32:58 -04:00
#### `NgModel` and value accessors
2017-03-11 08:44:25 -05:00
The details are specific to each kind of element and therefore the `NgModel` directive only works for an element
2017-04-30 16:10:32 -04:00
supported by a [ControlValueAccessor ](api/forms/ControlValueAccessor )
2017-02-22 13:09:39 -05:00
that adapts an element to this protocol.
Angular provides *value accessors* for all of the basic HTML form elements and the
2018-10-09 14:32:58 -04:00
[Forms ](guide/forms ) guide shows how to bind to them.
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
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 ).
2017-03-27 11:08:53 -04:00
2018-10-09 14:32:58 -04:00
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.
2017-03-27 11:08:53 -04:00
2018-10-09 14:32:58 -04:00
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:
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "NgModel-1" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
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 `<input>` value to uppercase:
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "uppercase" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
Here are all variations in action, including the uppercase version:
2017-03-11 08:44:25 -05:00
2019-11-11 17:47:51 -05:00
< div class = "lightbox" >
< img src = 'generated/images/guide/built-in-directives/ng-model-anim.gif' alt = "NgModel variations" >
< / div >
2017-02-22 13:09:39 -05:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a structural-directives}
2017-03-31 19:57:13 -04:00
2017-02-22 13:09:39 -05:00
## Built-in _structural_ directives
Structural directives are responsible for HTML layout.
2018-10-09 14:32:58 -04:00
They shape or reshape the DOM's structure, typically by adding, removing, and manipulating
2017-02-22 13:09:39 -05:00
the host elements to which they are attached.
2018-10-09 14:32:58 -04:00
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.
< div class = "alert is-helpful" >
2017-03-11 08:44:25 -05:00
The deep details of structural directives are covered in the
2018-10-09 14:32:58 -04:00
[Structural Directives ](guide/structural-directives ) guide,
which explains the following:
2017-03-11 08:44:25 -05:00
2018-10-09 14:32:58 -04:00
* Why you
[prefix the directive name with an asterisk (\*) ](guide/structural-directives#the-asterisk--prefix ).
* Using [`<ng-container>` ](guide/structural-directives#ngcontainer "<ng-container>" )
2017-02-22 13:09:39 -05:00
to group elements when there is no suitable host element for the directive.
2018-10-09 14:32:58 -04:00
* 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.
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
< / div >
2017-02-22 13:09:39 -05:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a ngIf}
2017-03-31 19:57:13 -04:00
2017-02-22 13:09:39 -05:00
### NgIf
2017-03-11 08:44:25 -05:00
2017-02-22 13:09:39 -05:00
You can add or remove an element from the DOM by applying an `NgIf` directive to
2018-10-09 14:32:58 -04:00
a host element.
2017-02-22 13:09:39 -05:00
Bind the directive to a condition expression like `isActive` in this example.
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "NgIf-1" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
< div class = "alert is-helpful" >
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
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 ).
2017-02-22 13:09:39 -05:00
2017-04-10 11:51:13 -04:00
< / div >
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
When the `isActive` expression returns a truthy value, `NgIf` adds the
`ItemDetailComponent` to the DOM.
When the expression is falsy, `NgIf` removes the `ItemDetailComponent`
2017-02-22 13:09:39 -05:00
from the DOM, destroying that component and all of its sub-components.
2017-03-11 08:44:25 -05:00
2018-10-09 14:32:58 -04:00
#### Show/hide vs. `NgIf`
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
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.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "NgIf-3" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
When you hide an element, that element and all of its descendants remain in the DOM.
2017-02-22 13:09:39 -05:00
All components for those elements stay in memory and
Angular may continue to check for changes.
2018-10-09 14:32:58 -04:00
You could be holding onto considerable computing resources and degrading performance
unnecessarily.
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
`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.
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
If you are hiding large component trees, consider `NgIf` as a more
efficient alternative to showing/hiding.
< div class = "alert is-helpful" >
2019-08-19 17:37:36 -04:00
For more information on `NgIf` and `ngIfElse` , see the [API documentation about NgIf ](api/common/NgIf ).
2018-10-09 14:32:58 -04:00
< / div >
2017-03-11 08:44:25 -05:00
#### Guard against null
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
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 `<div>` s.
The `currentCustomer` name appears only when there is a `currentCustomer` .
The `nullCustomer` will not be displayed as long as it is `null` .
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "NgIf-2" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "NgIf-2b" header = "src/app/app.component.html" > < / code-example >
2017-03-27 11:08:53 -04:00
2018-07-19 18:00:08 -04:00
< div class = "alert is-helpful" >
2017-02-22 13:09:39 -05:00
2017-03-11 08:44:25 -05:00
See also the
2018-10-09 14:32:58 -04:00
[safe navigation operator ](guide/template-syntax#safe-navigation-operator "Safe navigation operator (?. )") below.
2017-03-27 11:08:53 -04:00
2017-04-10 11:51:13 -04:00
< / div >
< hr / >
2017-02-22 13:09:39 -05:00
{@a ngFor}
2018-10-09 14:32:58 -04:00
### `NgFor`
2017-03-31 19:57:13 -04:00
2018-10-09 14:32:58 -04:00
`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.
2019-08-19 17:37:36 -04:00
The text assigned to `*ngFor` is the instruction that guides the repeater process.
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
The following example shows `NgFor` applied to a simple `<div>` . (Don't forget the asterisk (`*`) in front of `ngFor` .)
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "NgFor-1" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
You can also apply an `NgFor` to a component element, as in the following example.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "NgFor-2" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
{@a microsyntax}
2017-03-31 19:57:13 -04:00
2019-08-19 17:37:36 -04:00
< div class = "callout is-critical" >
< header > *ngFor microsyntax< / header >
2017-03-11 08:44:25 -05:00
2018-10-09 14:32:58 -04:00
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:
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
> *Take each item in the `items` array, store it in the local `item` looping variable, and
2017-02-22 13:09:39 -05:00
make it available to the templated HTML for each iteration.*
2018-10-09 14:32:58 -04:00
Angular translates this instruction into an `<ng-template>` around the host element,
then uses this template repeatedly to create a new set of elements and bindings for each `item`
2017-02-22 13:09:39 -05:00
in the list.
2018-10-09 14:32:58 -04:00
For more information about microsyntax, see the [Structural Directives ](guide/structural-directives#microsyntax ) guide.
2019-08-19 17:37:36 -04:00
< / div >
2017-02-22 13:09:39 -05:00
{@a template-input-variable}
{@a template-input-variables}
2017-03-31 19:57:13 -04:00
2018-10-09 14:32:58 -04:00
#### 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.
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
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 `<app-item-detail>` component.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "NgFor-1-2" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
For more information about template input variables, see
[Structural Directives ](guide/structural-directives#template-input-variable ).
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
#### `*ngFor` with `index`
2017-03-11 08:44:25 -05:00
2018-10-09 14:32:58 -04:00
The `index` property of the `NgFor` directive context
returns the zero-based index of the item in each iteration.
2017-02-22 13:09:39 -05:00
You can capture the `index` in a template input variable and use it in the template.
2018-10-09 14:32:58 -04:00
The next example captures the `index` in a variable named `i` and displays it with the item name.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "NgFor-3" header = "src/app/app.component.html" > < / code-example >
2017-03-27 11:08:53 -04:00
2018-07-19 18:00:08 -04:00
< div class = "alert is-helpful" >
2017-02-22 13:09:39 -05:00
2017-09-27 18:25:41 -04:00
`NgFor` is implemented by the `NgForOf` directive. Read more about the other `NgForOf` context values such as `last` , `even` ,
2017-08-17 05:40:46 -04:00
and `odd` in the [NgForOf API reference ](api/common/NgForOf ).
2017-02-22 13:09:39 -05:00
2017-04-10 11:51:13 -04:00
< / div >
2017-03-27 11:08:53 -04:00
2017-02-22 13:09:39 -05:00
{@a trackBy}
2018-10-09 14:32:58 -04:00
#### *ngFor with `trackBy`
2017-03-31 19:57:13 -04:00
2018-10-09 14:32:58 -04:00
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.
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
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` .
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.ts" region = "trackByItems" header = "src/app/app.component.ts" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
In the microsyntax expression, set `trackBy` to the `trackByItems()` method.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "trackBy" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
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.
2017-03-31 19:57:13 -04:00
2017-02-22 13:09:39 -05:00
* With no `trackBy` , both buttons trigger complete DOM element replacement.
2017-03-11 08:44:25 -05:00
* With `trackBy` , only changing the `id` triggers element replacement.
2017-02-22 13:09:39 -05:00
2019-11-11 17:47:51 -05:00
< div class = "lightbox" >
< img src = "generated/images/guide/built-in-directives/ngfor-trackby.gif" alt = "Animation of trackBy" >
< / div >
2017-02-22 13:09:39 -05:00
2019-06-18 17:03:19 -04:00
< div class = "alert is-helpful" >
Built-in directives use only public APIs; that is,
they do not have special access to any private APIs that other directives can't access.
< / div >
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a ngSwitch}
2018-10-09 14:32:58 -04:00
## The `NgSwitch` directives
2017-03-31 19:57:13 -04:00
2018-10-09 14:32:58 -04:00
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.
<!-- API Flagged -->
`NgSwitch` is actually a set of three, cooperating directives:
`NgSwitch` , `NgSwitchCase` , and `NgSwitchDefault` as in the following example.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "NgSwitch" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2019-11-11 17:47:51 -05:00
< div class = "lightbox" >
< img src = "generated/images/guide/built-in-directives/ngswitch.gif" alt = "Animation of NgSwitch" >
< / div >
2017-02-22 13:09:39 -05:00
2018-10-09 14:32:58 -04:00
`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.
2017-02-22 13:09:39 -05:00
2017-03-11 08:44:25 -05:00
**Bind to `[ngSwitch]` **. You'll get an error if you try to set `*ngSwitch` because
2017-02-22 13:09:39 -05:00
`NgSwitch` is an *attribute* directive, not a *structural* directive.
2018-10-09 14:32:58 -04:00
Rather than touching the DOM directly, it changes the behavior of its companion directives.
2017-02-22 13:09:39 -05:00
**Bind to `*ngSwitchCase` and `*ngSwitchDefault` **.
The `NgSwitchCase` and `NgSwitchDefault` directives are _structural_ directives
because they add or remove elements from the DOM.
2018-10-09 14:32:58 -04:00
* `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.
2017-02-22 13:09:39 -05:00
* `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* .
2018-10-09 14:32:58 -04:00
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.
2017-02-22 13:09:39 -05:00
Switch directives work as well with native elements and web components too.
2018-10-09 14:32:58 -04:00
For example, you could replace the `<app-best-item>` switch case with the following.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-directives/src/app/app.component.html" region = "NgSwitch-div" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a template-reference-variable}
2018-11-29 12:49:29 -05:00
{@a template-reference-variables--var-}
2017-02-22 13:09:39 -05:00
{@a ref-vars}
{@a ref-var}
2017-03-31 19:57:13 -04:00
2018-11-29 12:49:29 -05:00
## Template reference variables (`#var`)
2017-03-31 19:57:13 -04:00
2017-02-22 13:09:39 -05:00
A **template reference variable** is often a reference to a DOM element within a template.
2018-11-29 12:49:29 -05:00
It can also refer to a directive (which contains a component), an element, [TemplateRef ](api/core/TemplateRef ), or a < a href = "https://developer.mozilla.org/en-US/docs/Web/Web_Components" title = "MDN: Web Components" > web component</ a > .
For a demonstration of the syntax and code snippets in this section, see the < live-example name = "template-reference-variables" > template reference variables example< / live-example > .
2017-02-22 13:09:39 -05:00
Use the hash symbol (#) to declare a reference variable.
2018-11-29 12:49:29 -05:00
The following reference variable, `#phone` , declares a `phone` variable on an `<input>` element.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "template-reference-variables/src/app/app.component.html" region = "ref-var" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-11-29 12:49:29 -05:00
You can refer to a template reference variable anywhere in the component's template.
Here, a `<button>` further down the template refers to the `phone` variable.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "template-reference-variables/src/app/app.component.html" region = "ref-phone" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2017-05-08 23:47:34 -04:00
< h3 class = "no-toc" > How a reference variable gets its value< / h3 >
2017-02-22 13:09:39 -05:00
2018-11-29 12:49:29 -05:00
In most cases, Angular sets the reference variable's value to the element on which it is declared.
In the previous example, `phone` refers to the phone number `<input>` .
The button's click handler passes the `<input>` value to the component's `callPhone()` method.
2017-02-22 13:09:39 -05:00
2018-11-29 12:49:29 -05:00
The `NgForm` directive can change that behavior and set the value to something else. In the following example, the template reference variable, `itemForm` , appears three times separated
by HTML.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "template-reference-variables/src/app/app.component.html" region = "ngForm" header = "src/app/hero-form.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-11-29 12:49:29 -05:00
The reference value of itemForm, without the ngForm attribute value, would be
the [HTMLFormElement ](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement ).
2019-09-27 13:57:27 -04:00
There is, however, a difference between a Component and a Directive in that a `Component`
will be referenced without specifying the attribute value, and a `Directive` will not
2018-11-29 12:49:29 -05:00
change the implicit reference (that is, the element).
2017-02-22 13:09:39 -05:00
2018-11-29 12:49:29 -05:00
However, with `NgForm` , `itemForm` is a reference to the [NgForm ](api/forms/NgForm "API: NgForm" )
2017-02-22 13:09:39 -05:00
directive with the ability to track the value and validity of every control in the form.
2018-11-29 12:49:29 -05:00
The native `<form>` element doesn't have a `form` property, but the `NgForm` directive does, which allows disabling the submit button
if the `itemForm.form.valid` is invalid and passing the entire form control tree
to the parent component's `onSubmit()` method.
< h3 class = "no-toc" > Template reference variable considerations< / h3 >
2017-02-22 13:09:39 -05:00
2018-11-29 12:49:29 -05:00
A template _reference_ variable (`#phone`) is not the same as a template _input_ variable (`let phone`) such as in an [`*ngFor` ](guide/template-syntax#template-input-variable ).
See [_Structural Directives_ ](guide/structural-directives#template-input-variable ) for more information.
2017-02-22 13:09:39 -05:00
2018-11-29 12:49:29 -05:00
The scope of a reference variable is the entire template. So, don't define the same variable name more than once in the same template as the runtime value will be unpredictable.
2017-02-22 13:09:39 -05:00
2018-11-29 12:49:29 -05:00
#### Alternative syntax
2017-02-22 13:09:39 -05:00
You can use the `ref-` prefix alternative to `#` .
This example declares the `fax` variable as `ref-fax` instead of `#fax` .
2018-11-29 12:49:29 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "template-reference-variables/src/app/app.component.html" region = "ref-fax" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2017-03-30 15:04:18 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a inputs-outputs}
2017-03-31 19:57:13 -04:00
2018-12-03 13:42:53 -05:00
## `@Input()` and `@Output()` properties
2017-03-11 08:44:25 -05:00
2019-06-18 17:03:19 -04:00
`@Input()` and `@Output()` allow Angular to share data between the parent context
and child directives or components. An `@Input()` property is writable
while an `@Output()` property is observable.
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
Consider this example of a child/parent relationship:
2017-11-06 13:02:18 -05:00
2018-12-03 13:42:53 -05:00
```html
< parent-component >
< child-component > < / child-component >
< / parent-component >
```
Here, the `<child-component>` selector, or child directive, is embedded
within a `<parent-component>` , which serves as the child's context.
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
`@Input()` and `@Output()` act as
the API, or application programming interface, of the child
component in that they allow the child to
communicate with the parent. Think of `@Input()` and `@Output()` like ports
or doorways— `@Input()` is the doorway into the component allowing data
to flow in while `@Output()` is the doorway out of the component, allowing the
child component to send data out.
This section about `@Input()` and `@Output()` has its own < live-example name = "inputs-outputs" ></ live-example > . The following subsections highlight
key points in the sample app.
< div class = "alert is-helpful" >
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
#### `@Input()` and `@Output()` are independent
Though `@Input()` and `@Output()` often appear together in apps, you can use
them separately. If the nested
component is such that it only needs to send data to its parent, you wouldn't
need an `@Input()` , only an `@Output()` . The reverse is also true in that if the
2019-06-26 15:19:10 -04:00
child only needs to receive data from the parent, you'd only need `@Input()` .
2017-02-22 13:09:39 -05:00
2017-04-10 11:51:13 -04:00
< / div >
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
{@a input}
## How to use `@Input()`
Use the `@Input()` decorator in a child component or directive to let Angular know
that a property in that component can receive its value from its parent component.
It helps to remember that the data flow is from the perspective of the
child component. So an `@Input()` allows data to be input _into_ the
child component from the parent component.
2017-03-27 11:08:53 -04:00
2017-02-22 13:09:39 -05:00
2019-11-11 17:47:51 -05:00
< div class = "lightbox" >
< img src = "generated/images/guide/inputs-outputs/input.svg" alt = "Input data flow diagram" >
< / div >
2018-12-03 13:42:53 -05:00
To illustrate the use of `@Input()` , edit these parts of your app:
* The child component class and template
* The parent component class and template
### In the child
To use the `@Input()` decorator in a child component class, first import
`Input` and then decorate the property with `@Input()` :
2019-07-20 13:40:17 -04:00
< code-example path = "inputs-outputs/src/app/item-detail/item-detail.component.ts" region = "use-input" header = "src/app/item-detail/item-detail.component.ts" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
In this case, `@Input()` decorates the property < code class = "no-auto-link" > item</ code > , which has
a type of `string` , however, `@Input()` properties can have any type, such as
`number` , `string` , `boolean` , or `object` . The value for `item` will come from the parent component, which the next section covers.
Next, in the child component template, add the following:
2019-07-20 13:40:17 -04:00
< code-example path = "inputs-outputs/src/app/item-detail/item-detail.component.html" region = "property-in-template" header = "src/app/item-detail/item-detail.component.html" > < / code-example >
2018-12-03 13:42:53 -05:00
2017-02-22 13:09:39 -05:00
2017-03-27 11:08:53 -04:00
2018-12-03 13:42:53 -05:00
### In the parent
2017-03-27 11:08:53 -04:00
2018-12-03 13:42:53 -05:00
The next step is to bind the property in the parent component's template.
In this example, the parent component template is `app.component.html` .
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
First, use the child's selector, here `<app-item-detail>` , as a directive within the
parent component template. Then, use [property binding ](guide/template-syntax#property-binding )
to bind the property in the child to the property of the parent.
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "inputs-outputs/src/app/app.component.html" region = "input-parent" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
Next, in the parent component class, `app.component.ts` , designate a value for `currentItem` :
2017-03-11 08:44:25 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "inputs-outputs/src/app/app.component.ts" region = "parent-property" header = "src/app/app.component.ts" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
With `@Input()` , Angular passes the value for `currentItem` to the child so that `item` renders as `Television` .
2017-11-06 13:02:18 -05:00
2018-12-03 13:42:53 -05:00
The following diagram shows this structure:
2017-11-06 13:02:18 -05:00
2019-11-11 17:47:51 -05:00
< div class = "lightbox" >
< img src = "generated/images/guide/inputs-outputs/input-diagram-target-source.svg" alt = "Property binding diagram" >
< / div >
2018-12-03 13:42:53 -05:00
The target in the square brackets, `[]` , is the property you decorate
with `@Input()` in the child component. The binding source, the part
to the right of the equal sign, is the data that the parent
component passes to the nested component.
The key takeaway is that when binding to a child component's property in a parent component— that is, what's
in square brackets— you must
decorate the property with `@Input()` in the child component.
< div class = "alert is-helpful" >
#### `OnChanges` and `@Input()`
To watch for changes on an `@Input()` property, use
`OnChanges` , one of Angular's [lifecycle hooks ](guide/lifecycle-hooks#onchanges ).
`OnChanges` is specifically designed to work with properties that have the
`@Input()` decorator. See the [`OnChanges` ](guide/lifecycle-hooks#onchanges ) section of the [Lifecycle Hooks ](guide/lifecycle-hooks ) guide for more details and examples.
< / div >
{@a output}
## How to use `@Output()`
Use the `@Output()` decorator in the child component or directive to allow data to flow from
the child _out_ to the parent.
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
An `@Output()` property should normally be initialized to an Angular [`EventEmitter` ](api/core/EventEmitter ) with values flowing out of the component as [events ](#event-binding ).
2017-03-11 08:44:25 -05:00
2017-02-22 13:09:39 -05:00
2019-11-11 17:47:51 -05:00
< div class = "lightbox" >
< img src = "generated/images/guide/inputs-outputs/output.svg" alt = "Output diagram" >
< / div >
2018-12-03 13:42:53 -05:00
Just like with `@Input()` , you can use `@Output()`
on a property of the child component but its type should be
`EventEmitter` .
`@Output()` marks a property in a child component as a doorway
through which data can travel from the child to the parent.
The child component then has to raise an event so the
parent knows something has changed. To raise an event,
`@Output()` works hand in hand with `EventEmitter` ,
which is a class in `@angular/core` that you
use to emit custom events.
When you use `@Output()` , edit these parts of your app:
* The child component class and template
* The parent component class and template
2017-11-06 13:02:18 -05:00
2018-12-03 13:42:53 -05:00
The following example shows how to set up an `@Output()` in a child
component that pushes data you enter in an HTML `<input>` to an array in the
parent component.
2017-11-06 13:02:18 -05:00
2018-12-03 13:42:53 -05:00
< div class = "alert is-helpful" >
2017-11-06 13:02:18 -05:00
2018-12-03 13:42:53 -05:00
The HTML element `<input>` and the Angular decorator `@Input()`
are different. This documentation is about component communication in Angular as it pertains to `@Input()` and `@Output()` . For more information on the HTML element `<input>` , see the [W3C Recommendation ](https://www.w3.org/TR/html5/sec-forms.html#the-input-element ).
2017-11-06 13:02:18 -05:00
< / div >
2018-12-03 13:42:53 -05:00
### In the child
This example features an `<input>` where a user can enter a value and click a `<button>` that raises an event. The `EventEmitter` then relays the data to the parent component.
First, be sure to import `Output` and `EventEmitter`
in the child component class:
```js
import { Output, EventEmitter } from '@angular/core';
```
2017-11-06 13:02:18 -05:00
2018-12-03 13:42:53 -05:00
Next, still in the child, decorate a property with `@Output()` in the component class.
The following example `@Output()` is called `newItemEvent` and its type is
`EventEmitter` , which means it's an event.
2017-11-06 13:02:18 -05:00
2017-03-11 08:44:25 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "inputs-outputs/src/app/item-output/item-output.component.ts" region = "item-output" header = "src/app/item-output/item-output.component.ts" > < / code-example >
2017-03-27 11:08:53 -04:00
2018-12-03 13:42:53 -05:00
The different parts of the above declaration are as follows:
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
* `@Output()` — a decorator function marking the property as a way for data to go from the child to the parent
* `newItemEvent` — the name of the `@Output()`
* `EventEmitter<string>` — the `@Output()` 's type
* `new EventEmitter<string>()` — tells Angular to create a new event emitter and that the data it emits is of type string. The type could be any type, such as `number` , `boolean` , and so on. For more information on `EventEmitter` , see the [EventEmitter API documentation ](api/core/EventEmitter ).
Next, create an `addNewItem()` method in the same component class:
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "inputs-outputs/src/app/item-output/item-output.component.ts" region = "item-output-class" header = "src/app/item-output/item-output.component.ts" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
The `addNewItem()` function uses the `@Output()` , `newItemEvent` ,
to raise an event in which it emits the value the user
types into the `<input>` . In other words, when
the user clicks the add button in the UI, the child lets the parent know
about the event and gives that data to the parent.
#### In the child's template
The child's template has two controls. The first is an HTML `<input>` with a
[template reference variable ](guide/template-syntax#ref-var ) , `#newItem` ,
where the user types in an item name. Whatever the user types
into the `<input>` gets stored in the `#newItem` variable.
2019-07-20 13:40:17 -04:00
< code-example path = "inputs-outputs/src/app/item-output/item-output.component.html" region = "child-output" header = "src/app/item-output/item-output.component.html" > < / code-example >
2018-12-03 13:42:53 -05:00
The second element is a `<button>`
with an [event binding ](guide/template-syntax#event-binding ). You know it's
an event binding because the part to the left of the equal
sign is in parentheses, `(click)` .
The `(click)` event is bound to the `addNewItem()` method in the child component class which
takes as its argument whatever the value of `#newItem` is.
Now the child component has an `@Output()`
for sending data to the parent and a method for raising an event.
The next step is in the parent.
### In the parent
In this example, the parent component is `AppComponent` , but you could use
any component in which you could nest the child.
The `AppComponent` in this example features a list of `items`
in an array and a method for adding more items to the array.
2019-07-20 13:40:17 -04:00
< code-example path = "inputs-outputs/src/app/app.component.ts" region = "add-new-item" header = "src/app/app.component.ts" > < / code-example >
2018-12-03 13:42:53 -05:00
The `addItem()` method takes an argument in the form of a string
and then pushes, or adds, that string to the `items` array.
#### In the parent's template
Next, in the parent's template, bind the parent's
method to the child's event. Put the child selector, here `<app-item-output>` ,
within the parent component's
template, `app.component.html` .
2019-07-20 13:40:17 -04:00
< code-example path = "inputs-outputs/src/app/app.component.html" region = "output-parent" header = "src/app/app.component.html" > < / code-example >
2018-12-03 13:42:53 -05:00
The event binding, `(newItemEvent)='addItem($event)'` , tells
Angular to connect the event in the child, `newItemEvent` , to
the method in the parent, `addItem()` , and that the event that the child
is notifying the parent about is to be the argument of `addItem()` .
In other words, this is where the actual hand off of data takes place.
The `$event` contains the data that the user types into the `<input>`
in the child template UI.
Now, in order to see the `@Output()` working, add the following to the parent's template:
2019-08-19 17:37:36 -04:00
```html
2018-12-03 13:42:53 -05:00
< ul >
< li * ngFor = "let item of items" > {{item}}< / li >
< / ul >
```
The `*ngFor` iterates over the items in the `items` array. When you enter a value in the child's `<input>` and click the button, the child emits the event and the parent's `addItem()` method pushes the value to the `items` array and it renders in the list.
2017-03-27 11:08:53 -04:00
2018-12-03 13:42:53 -05:00
## `@Input()` and `@Output()` together
You can use `@Input()` and `@Output()` on the same child component as in the following:
2019-07-20 13:40:17 -04:00
< code-example path = "inputs-outputs/src/app/app.component.html" region = "together" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
The target, `item` , which is an `@Input()` property in the child component class, receives its value from the parent's property, `currentItem` . When you click delete, the child component raises an event, `deleteRequest` , which is the argument for the parent's `crossOffItem()` method.
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
The following diagram is of an `@Input()` and an `@Output()` on the same
child component and shows the different parts of each:
2017-03-11 08:44:25 -05:00
2019-11-11 17:47:51 -05:00
< div class = "lightbox" >
< img src = "generated/images/guide/inputs-outputs/input-output-diagram.svg" alt = "Input/Output diagram" >
< / div >
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
As the diagram shows, use inputs and outputs together in the same manner as using them separately. Here, the child selector is `<app-input-output>` with `item` and `deleteRequest` being `@Input()` and `@Output()`
properties in the child component class. The property `currentItem` and the method `crossOffItem()` are both in the parent component class.
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
To combine property and event bindings using the banana-in-a-box
syntax, `[()]` , see [Two-way Binding ](guide/template-syntax#two-way ).
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
For more detail on how these work, see the previous sections on [Input ](guide/template-syntax#input ) and [Output ](guide/template-syntax#output ). To see it in action, see the < live-example name = "inputs-outputs" > Inputs and Outputs Example</ live-example > .
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
## `@Input()` and `@Output()` declarations
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
Instead of using the `@Input()` and `@Output()` decorators
to declare inputs and outputs, you can identify
members in the `inputs` and `outputs` arrays
of the directive metadata, as in this example:
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "inputs-outputs/src/app/in-the-metadata/in-the-metadata.component.ts" region = "metadata" header = "src/app/in-the-metadata/in-the-metadata.component.ts" > < / code-example >
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
While declaring `inputs` and `outputs` in the `@Directive` and `@Component`
metadata is possible, it is a better practice to use the `@Input()` and `@Output()`
class decorators instead, as follows:
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "inputs-outputs/src/app/input-output/input-output.component.ts" region = "input-output" header = "src/app/input-output/input-output.component.ts" > < / code-example >
2018-12-03 13:42:53 -05:00
See the [Decorate input and output properties ](guide/styleguide#decorate-input-and-output-properties ) section of the
[Style Guide ](guide/styleguide ) for details.
2017-02-22 13:09:39 -05:00
2017-03-27 11:08:53 -04:00
2018-07-19 18:00:08 -04:00
< div class = "alert is-helpful" >
2017-03-27 11:08:53 -04:00
2018-12-03 13:42:53 -05:00
If you get a template parse error when trying to use inputs or outputs, but you know that the
properties do indeed exist, double check
that your properties are annotated with `@Input()` / `@Output()` or that you've declared
them in an `inputs` /`outputs` array:
2017-02-22 13:09:39 -05:00
2019-08-19 17:37:36 -04:00
< code-example language = "bash" >
2018-12-03 13:42:53 -05:00
Uncaught Error: Template parse errors:
Can't bind to 'item' since it isn't a known property of 'app-item-detail'
2017-03-27 11:08:53 -04:00
< / code-example >
2017-04-10 11:51:13 -04:00
< / div >
2017-02-22 13:09:39 -05:00
2018-12-03 13:42:53 -05:00
{@a aliasing-io}
## Aliasing inputs and outputs
Sometimes the public name of an input/output property should be different from the internal name. While it is a best practice to avoid this situation, Angular does
offer a solution.
### Aliasing in the metadata
Alias inputs and outputs in the metadata using a colon-delimited (`:`) string with
the directive property name on the left and the public alias on the right:
2019-07-20 13:40:17 -04:00
< code-example path = "inputs-outputs/src/app/aliasing/aliasing.component.ts" region = "alias" header = "src/app/aliasing/aliasing.component.ts" > < / code-example >
2018-12-03 13:42:53 -05:00
### Aliasing with the `@Input()`/`@Output()` decorator
You can specify the alias for the property name by passing the alias name to the `@Input()` /`@Output()` decorator. The internal name remains as usual.
2019-07-20 13:40:17 -04:00
< code-example path = "inputs-outputs/src/app/aliasing/aliasing.component.ts" region = "alias-input-output" header = "src/app/aliasing/aliasing.component.ts" > < / code-example >
2018-12-03 13:42:53 -05:00
2017-03-30 15:04:18 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-02-22 13:09:39 -05:00
{@a expression-operators}
2017-03-31 19:57:13 -04:00
2017-02-22 13:09:39 -05:00
## Template expression operators
2017-03-11 08:44:25 -05:00
2019-01-08 15:58:23 -05:00
The Angular template expression language employs a subset of JavaScript syntax supplemented with a few special operators
for specific scenarios. The next sections cover three of these operators:
* [pipe ](guide/template-syntax#pipe )
* [safe navigation operator ](guide/template-syntax#safe-navigation-operator )
* [non-null assertion operator ](guide/template-syntax#non-null-assertion-operator )
2017-02-22 13:09:39 -05:00
{@a pipe}
2017-03-31 19:57:13 -04:00
2019-01-08 15:58:23 -05:00
### The pipe operator (`|`)
2017-03-11 08:44:25 -05:00
2017-02-22 13:09:39 -05:00
The result of an expression might require some transformation before you're ready to use it in a binding.
2019-01-08 15:58:23 -05:00
For example, you might display a number as a currency, change text to uppercase, or filter a list and sort it.
2017-02-22 13:09:39 -05:00
Pipes are simple functions that accept an input value and return a transformed value.
2019-01-08 15:58:23 -05:00
They're easy to apply within template expressions, using the pipe operator (`|`):
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "template-expression-operators/src/app/app.component.html" region = "uppercase-pipe" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
The pipe operator passes the result of an expression on the left to a pipe function on the right.
You can chain expressions through multiple pipes:
2019-07-20 13:40:17 -04:00
< code-example path = "template-expression-operators/src/app/app.component.html" region = "pipe-chain" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2017-03-31 19:57:13 -04:00
And you can also [apply parameters ](guide/pipes#parameterizing-a-pipe ) to a pipe:
2019-07-20 13:40:17 -04:00
< code-example path = "template-expression-operators/src/app/app.component.html" region = "date-pipe" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2017-03-11 08:44:25 -05:00
The `json` pipe is particularly helpful for debugging bindings:
2017-03-27 11:08:53 -04:00
2019-07-20 13:40:17 -04:00
< code-example path = "template-expression-operators/src/app/app.component.html" region = "json-pipe" header = "src/app/app.component.html" > < / code-example >
2017-03-27 11:08:53 -04:00
2019-01-08 15:58:23 -05:00
The generated output would look something like this:
2017-03-11 08:44:25 -05:00
< code-example language = "json" >
2019-01-08 15:58:23 -05:00
{ "name": "Telephone",
"manufactureDate": "1980-02-25T05:00:00.000Z",
"price": 98 }
2017-03-11 08:44:25 -05:00
< / code-example >
2019-01-08 15:58:23 -05:00
< div class = "alert is-helpful" >
2017-03-30 15:04:18 -04:00
2019-08-19 17:37:36 -04:00
The pipe operator has a higher precedence than the ternary operator (`?:`),
2019-01-08 15:58:23 -05:00
which means `a ? b : c | x` is parsed as `a ? b : (c | x)` .
Nevertheless, for a number of reasons,
the pipe operator cannot be used without parentheses in the first and second operands of `?:` .
A good practice is to use parentheses in the third operand too.
< / div >
2017-02-22 13:09:39 -05:00
2017-03-31 19:57:13 -04:00
2019-01-08 15:58:23 -05:00
< hr / >
2017-02-22 13:09:39 -05:00
2019-01-08 15:58:23 -05:00
{@a safe-navigation-operator}
2017-02-22 13:09:39 -05:00
2019-01-08 15:58:23 -05:00
### The safe navigation operator ( `?` ) and null property paths
2017-02-22 13:09:39 -05:00
2019-01-08 15:58:23 -05:00
The Angular safe navigation operator, `?` , guards against `null` and `undefined`
values in property paths. Here, it protects against a view render failure if `item` is `null` .
2017-02-22 13:09:39 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "template-expression-operators/src/app/app.component.html" region = "safe" header = "src/app/app.component.html" > < / code-example >
2017-02-22 13:09:39 -05:00
2019-01-08 15:58:23 -05:00
If `item` is `null` , the view still renders but the displayed value is blank; you see only "The item name is:" with nothing after it.
2017-02-22 13:09:39 -05:00
2019-01-08 15:58:23 -05:00
Consider the next example, with a `nullItem` .
2017-02-22 13:09:39 -05:00
< code-example language = "html" >
2019-01-08 15:58:23 -05:00
The null item name is {{nullItem.name}}
2017-03-11 08:44:25 -05:00
< / code-example >
2019-01-08 15:58:23 -05:00
Since there is no safe navigation operator and `nullItem` is `null` , JavaScript and Angular would throw a `null` reference error and break the rendering process of Angular:
2017-03-11 08:44:25 -05:00
2019-08-19 17:37:36 -04:00
< code-example language = "bash" >
2019-01-08 15:58:23 -05:00
TypeError: Cannot read property 'name' of null.
2017-03-27 11:08:53 -04:00
< / code-example >
2017-02-22 13:09:39 -05:00
2019-01-08 15:58:23 -05:00
Sometimes however, `null` values in the property
path may be OK under certain circumstances,
especially when the value starts out null but the data arrives eventually.
2017-02-22 13:09:39 -05:00
2019-01-08 15:58:23 -05:00
With the safe navigation operator, `?` , Angular stops evaluating the expression when it hits the first `null` value and renders the view without errors.
2017-02-22 13:09:39 -05:00
It works perfectly with long property paths such as `a?.b?.c?.d` .
2017-06-09 04:05:16 -04:00
2017-03-30 15:04:18 -04:00
2017-04-10 11:51:13 -04:00
< hr / >
2017-03-31 19:57:13 -04:00
2017-05-22 16:00:38 -04:00
{@a non-null-assertion-operator}
2019-01-08 15:58:23 -05:00
### The non-null assertion operator ( `!` )
2017-05-22 16:00:38 -04:00
2019-01-08 15:58:23 -05:00
As of Typescript 2.0, you can enforce [strict null checking ](http://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html "Strict null checking in TypeScript" ) with the `--strictNullChecks` flag. TypeScript then ensures that no variable is unintentionally null or undefined.
2017-05-22 16:00:38 -04:00
2019-01-08 15:58:23 -05:00
In this mode, typed variables disallow `null` and `undefined` by default. The type checker throws an error if you leave a variable unassigned or try to assign `null` or `undefined` to a variable whose type disallows `null` and `undefined` .
2017-06-12 15:50:47 -04:00
2019-01-08 15:58:23 -05:00
The type checker also throws an error if it can't determine whether a variable will be `null` or undefined at runtime. You tell the type checker not to throw an error by applying the postfix
[non-null assertion operator, ! ](http://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator "Non-null assertion operator" ).
2017-06-12 15:50:47 -04:00
2019-01-08 15:58:23 -05:00
The Angular non-null assertion operator, `!` , serves the same purpose in
an Angular template. For example, after you use [*ngIf ](guide/template-syntax#ngIf )
to check that `item` is defined, you can assert that
`item` properties are also defined.
2017-05-22 16:00:38 -04:00
2019-07-20 13:40:17 -04:00
< code-example path = "template-expression-operators/src/app/app.component.html" region = "non-null" header = "src/app/app.component.html" > < / code-example >
2017-05-22 16:00:38 -04:00
2017-06-12 15:50:47 -04:00
When the Angular compiler turns your template into TypeScript code,
2019-01-08 15:58:23 -05:00
it prevents TypeScript from reporting that `item` might be `null` or `undefined` .
2017-06-12 15:50:47 -04:00
2019-01-08 15:58:23 -05:00
Unlike the [_safe navigation operator_ ](guide/template-syntax#safe-navigation-operator "Safe navigation operator (? )"),
the non-null assertion operator does not guard against `null` or `undefined` .
Rather, it tells the TypeScript type checker to suspend strict `null` checks for a specific property expression.
2017-06-12 15:50:47 -04:00
2019-01-08 15:58:23 -05:00
The non-null assertion operator, `!` , is optional with the exception that you must use it when you turn on strict null checks.
2017-05-22 16:00:38 -04:00
2017-06-09 04:05:16 -04:00
< a href = "#top-of-page" > back to top< / a >
< hr / >
2019-01-14 13:56:28 -05:00
{@a built-in-template-functions}
## Built-in template functions
2017-12-12 15:51:38 -05:00
{@a any-type-cast-function}
2019-01-14 13:56:28 -05:00
### The `$any()` type cast function
2017-12-12 15:51:38 -05:00
2019-08-19 17:37:36 -04:00
Sometimes a binding expression triggers a type error during [AOT compilation ](guide/aot-compiler ) and it is not possible or difficult to fully specify the type.
To silence the error, you can use the `$any()` cast function to cast
the expression to the [`any` type ](http://www.typescriptlang.org/docs/handbook/basic-types.html#any ) as in the following example:
2017-12-12 15:51:38 -05:00
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-template-functions/src/app/app.component.html" region = "any-type-cast-function-1" header = "src/app/app.component.html" > < / code-example >
2017-12-12 15:51:38 -05:00
2019-01-14 13:56:28 -05:00
When the Angular compiler turns this template into TypeScript code,
it prevents TypeScript from reporting that `bestByDate` is not a member of the `item`
object when it runs type checking on the template.
2017-12-12 15:51:38 -05:00
2019-01-14 13:56:28 -05:00
The `$any()` cast function also works with `this` to allow access to undeclared members of
2017-12-12 15:51:38 -05:00
the component.
2019-07-20 13:40:17 -04:00
< code-example path = "built-in-template-functions/src/app/app.component.html" region = "any-type-cast-function-2" header = "src/app/app.component.html" > < / code-example >
2017-12-12 15:51:38 -05:00
2019-01-14 13:56:28 -05:00
The `$any()` cast function works anywhere in a binding expression where a method call is valid.
2019-06-26 02:16:04 -04:00
## SVG in templates
2019-06-30 02:34:15 -04:00
It is possible to use SVG as valid templates in Angular. All of the template syntax below is
applicable to both SVG and HTML. Learn more in the SVG [1.1 ](https://www.w3.org/TR/SVG11/ ) and
[2.0 ](https://www.w3.org/TR/SVG2/ ) specifications.
2019-06-26 02:16:04 -04:00
Why would you use SVG as template, instead of simply adding it as image to your application?
2019-06-30 02:34:15 -04:00
When you use an SVG as the template, you are able to use directives and bindings just like with HTML
templates. This means that you will be able to dynamically generate interactive graphics.
2019-06-26 02:16:04 -04:00
Refer to the sample code snippet below for a syntax example:
2019-07-20 13:40:17 -04:00
< code-example path = "template-syntax/src/app/svg.component.ts" header = "src/app/svg.component.ts" > < / code-example >
2019-06-26 02:16:04 -04:00
2019-08-19 17:37:36 -04:00
Add the following code to your `svg.component.svg` file:
2019-06-26 02:16:04 -04:00
2019-07-20 13:40:17 -04:00
< code-example path = "template-syntax/src/app/svg.component.svg" header = "src/app/svg.component.svg" > < / code-example >
2019-06-26 02:16:04 -04:00
2019-06-30 02:34:15 -04:00
Here you can see the use of a `click()` event binding and the property binding syntax
(`[attr.fill]="fillColor"`).