"intro":"Displaying data is job number one for any good application. In Angular, you bind data to elements in HTML templates and Angular automatically updates the UI as data changes."
"intro":"In Angular, we display data by binding component properties to elements in HTML templates using interpolation and other forms of Property Binding."
Angular components use properties to identify the data associated with the component. For example, a hero component may have properties such as a hero name. Let's walk through how we'd display a property, a list of properties, and then conditionally show content based on state. We'll end up with a UI that looks like this:
The simple technique for displaying the data from a component property is to bind the property name through interpolation. With interpolation, you put the property name in the view template enclosed in double curly braces: { { myHero } } .
To see this working, follow the steps in the Getting Started section. Then modify the app.ts file as follows:
:markdown
## Showing component properties with interpolation
The easiest way to display a component property
is to bind the property name through interpolation.
With interpolation, we put the property name in the view template enclosed in double curly braces: { { myHero } } .
import {Component, View, bootstrap} from 'angular2/angular2';
Let's build a small illustrative example together.
@Compo
nent({
selector: 'my-app'
})
@View({
template: '<h1>{{title}}</h1><h2>My favorite hero is: {{myHero}}</h2>'
})
class AppComponent {
title: string = 'Tour of Heroes';
myHero: string = 'Windstorm';
}
bootstrap(AppComponent);
Create a new project folder (`displaying-data`) and follow the steps in the [QuickStart](../quickstart.html).
:markdown
This code defines a component and associated view for the app. The component now has two properties: title and myHero. The view defines a template that displays those two properties using interpolation:
<h1>{{title}}</h1><h2>My favorite hero is: {{myHero}}</h2>
:markdown
Angular automatically pulls the value of the title and myHero properties from the component and inserts those values into the browser. Angular automatically updates the display whenever the property value changes.
One thing to notice here is that we haven't called **new** to create an instance of the AppComponent class. When defining the component in app.ts, we identified a selector named ‘my-app’. As shown in the Getting Started section, we used an HTML element named 'my-app' in the index.html file. By associating the AppComponent with the element named 'my-app' in the DOM, Angular knows to automatically call new on AppComponent and bind its properties to that part of the template.
There are two techniques for defining a template for the view associated with a component. The template can be defined inline using the template property, as shown in the example above. Or the template can be defined in a separate HTML file and referenced using the templateUrl property.
In either case, when building templates the data bindings have access to the same scope of properties as the component class. Here, the class AppComponent and has two properties: title and myHero. The template can bind to either or both of those properties.
## Showing an array property with NgFor
Moving up from a single property, let’s create an array to display as a list. And let’s move the initialization of the properties to the class constructor.
We can use the NgFor directive in the template to display each item in this array as shown below. Add the NgFor directive to one of the DOM elements. Angular then creates a copy of that DOM element for each item in the array.
code-example(format="linenums" language="html").
template: `
<h1>{{title}}</h1>
<h2>My favorite hero is: {{myHero}}</h2>
<p>Heroes:</p>
<ul>
<li *ng-for="#hero of heroes">
{{ hero }}
</li>
</ul>
`
Then modify the `app.ts` file by changing the template and the body of the component.
When we're done, it should look like this:
:markdown
Notice that we are now using the backtick instead of the single quote to enclose the template. This allows us to define multiple lines of HTML for the template.
We added the NgFor to the li element, so Angular will define an li element for each item in the list. However, by default Angular does not automatically include the NgFor directive. We have to do that manually by making two changes to the app.ts file.
First, we need to add NgFor to the import statement as follows:
```
import {Component, View, bootstrap, NgFor} from 'angular2/angular2';
```
Second, we need to define NgFor as a directive accessible to the view as follows:
The heroes then appear in the view as an unordered list. Angular will automatically update the display any time that the list changes. Add a new item and it appears in the list. Delete an item and Angular deletes the item from the list. Reorder items and Angular makes the corresponding reorder of the DOM list.
Let's look again at the few lines of HTML that perform this operation:
code-example(format="linenums" language="html").
<li *ng-for="#hero of heroes">
{{ hero }}
</li>
:markdown
We added two properties to the formerly empty component: `title` and `myHero`.
:markdown
Breaking this down:
- *ng-for : creates a DOM element for each item in an [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) like an array
- #hero : defines a local variable that refers to individual values of the iterable as 'hero'
- of heros : the iterable to use is called 'heroes' in the current component
Using this NgFor syntax, we can display data from any iterable object.
## Creating a class for the data
Before we get too much further, note that putting our data model directly in our component doesn’t follow best practices. We should separate the concerns by having another class serve the role of model and use it in the component.
We’ll add this class to the app.ts file to minimize the number of files required for this demo. But you would want to define a separate hero.ts file for this.
```
class Hero {
id: number;
name: string;
}
```
Here we define a Hero class with two properties: id and name.
We can then change the AppComponent to use this new class as a data type:
```
class AppComponent {
title: string;
myHero: Hero;
heroes: Hero[];
constructor() {
this.title = 'Tour of Heroes';
this.myHero = {
id: 1,
name: 'Windstorm'
};
this.heroes = [
{ "id": 1, "name": "Windstorm" },
{ "id": 15, "name": "Magneta" },
{ "id": 20, "name": "Tornado" }
];
}
}
```
We also need to change the template to access the appropriate class property:
code-example(format="linenums" language="html").
@View({
template: `
<h1>{{title}}</h1>
<h2>My favorite hero is: {{myHero.name}}</h2>
<p>Heroes:</p>
<ul>
<li *ng-for="#hero of heroes">
{{ hero.name }}
</li>
</ul>
`,
directives: [NgFor]
})
:markdown
The application should work as before, but it now uses the Hero class to define the hero properties.
## Conditionally displaying data with NgIf
There may be times that the app needs to conditionally display data. For example, only display a message if a specific condition is true. We can conditionally display data using NgIf. The NgIf directive adds or removes elements from the DOM based on an expression.
See it in action by adding a paragraph at the end of the template as shown below:
```
<p *ng-if="heroes.length > 3">There are many heroes!</p>
```
If the list of heroes has more than 3 items, the paragraph is added to the DOM and the message appears. If there are 3 or fewer items, the paragraph won’t be added to the DOM and no message appears.
Our revised template displays the two component properties using the double curly brace
interpolation:
As with the NgFor, we’ll need to add the NgIf directive so Angular knows to include it. Add it to the import:
```
import {Component, View, bootstrap, NgFor, NgIf} from 'angular2/angular2';
```
And add it to the directives array:
```
directives: [NgFor, NgIf]
```
Since there are four items in the array, the message should appear. Delete one of the elements from the array, refresh the browser and the message should no longer appear.
## Using the CORE_DIRECTIVES Constant
In addition to NgFor and NgIf, there are other core Angular directives that are often used in Angular apps such as NgClass and NgSwitch. Instead of importing each Angular core directive separately as we did with NgFor and NgIf, Angular provides a constant called CORE_DIRECTIVES. This constant defines a collection of the Angular core directives. We can then use this constant instead of enumerating each built-in directive as part of the import statement and @View annotation.
Using the CORE_DIRECTIVES constant we can change our import statement to:
```
import {Component, View, bootstrap, CORE_DIRECTIVES} from 'angular2/angular2';
```
And we can change our @View annotation to:
```
directives: [CORE_DIRECTIVES]
```
Use this constant instead of enumerating each Angular core directive any time you plan to use the built-in directives in your view.
## Summary
- You now know how to:
- Use interpolation with the double curly braces to display a single component property,
- Use NgFor to display a list of items from an array,
- Use a TypeScript class to define the data for your component and display properties of that class,
- Use NgIf to conditionally display data based on an expression.
- And use the CORE_DIRECTIVES constant to simplify specification of the core Angular directives.
Use these techniques any time you need to display data in the view.
The resulting app.ts file is as follows:
code-example(format="linenums" language="html").
import {Component, View, bootstrap, CORE_DIRECTIVES} from 'angular2/angular2';
@Component({
selector: 'my-app'
})
@View({
template: `
<h1>{{title}}</h1>
<h2>My favorite hero is: {{myHero.name}}</h2>
<p>Heroes:</p>
<ul>
<li *ng-for="#hero of heroes">
{{ hero.name }}
</li>
</ul>
<p *ng-if="heroes.length > 3">There are many heroes!</p>