(docs) devguide-displaying-data: created new page and styled text, as a workaround in one sentence I placed spaces between double curlies {{ }} to render without breaking jade

This commit is contained in:
Ward Bell 2015-10-19 09:38:35 -07:00 committed by Naomi Black
parent 359904d0d0
commit 17ec689397
2 changed files with 263 additions and 336 deletions

View File

@ -1,347 +1,274 @@
include ../../../../_includes/_util-fns
.l-main-section
:markdown
## Displaying component properties
h2#section-displaying-controller-properties Displaying controller properties
p.
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:
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:
figure.image-display
img(src='/resources/images/examples/displaying-data-example1.png' alt="Example of Todo App")
img(src="/resources/images/devguide/displaying-data/final.png" alt="Final UI")
.callout.is-helpful
header Typescript vs ES5
p.
Although we work through the examples in TypeScript, you can also use
regular ES5. Click the ES5 link in any code box to see the ES5 JavaScript
version. Note that in ES5, you'd want to name your files <code>.js</code> rather than
<code>.ts</code>.
:markdown
Showing properties with interpolation
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: &#123; &#123; myHero &#125; &#125; .
.l-main-section
h2#section-create-an-entry-point Create an entry point
To see this working, follow the steps in the Getting Started section. Then modify the app.ts file as follows:
p Open your favorite editor and create a <code>show-properties.html</code> file with the content:
code-example(format="linenums" language="html" escape="html").
import {Component, View, bootstrap} from 'angular2/angular2';
code-example(language="html" escape="html").
<display></display>
@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);
p
| The <code>&lt;display&gt;</code> component here acts as the site where you'll insert your application.
| We'll assume a structure like this for the rest of the examples here and just focus on the parts that
| are different.
: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:
.l-main-section
h2#section-showing-properties-with-interpolation Showing properties with interpolation
p.text-body
| The simple method for binding text into templates is through interpolation where you put the name of a property
| inside <strong>{{ }}</strong>.
code-example(format="linenums" language="html" escape="html").
<h1>{{title}}</h1><h2>My favorite hero is: {{myHero}}</h2>
p To see this working, create another file, <code>show-properties.ts</code>, and add the following:
: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.
code-tabs
code-pane(language="javascript" name="TypeScript" format="linenums").
// TypeScript
import {Component, View, bootstrap} from 'angular2/angular2';
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.
@Component({
selector: 'display'
})
@View({
template: `
&lt;p&gt;My name: {{ myName }}&lt;/p&gt;
`
})
class DisplayComponent {
myName: string;
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.
constructor() {
this.myName = "Alice";
}
}
code-pane(language="javascript" name="ES5" format="linenums").
// ES5
function DisplayComponent() {
this.myName = "Alice";
}
DisplayComponent.annotations = [
new angular.ComponentAnnotation({
selector: "display"
}),
new angular.ViewAnnotation({
template:
'&lt;p&gt;My name: {{ myName }}&lt;/p&gt;'
})
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, lets create an array to display as a list. And lets move the initialization of the properties to the class constructor.
code-example(format="linenums").
class AppComponent {
title: string;
myHero: string;
heroes: Array<string>;
constructor() {
this.title = 'Tour of Heroes';
this.myHero = 'Windstorm';
this.heroes = ['Magenta', 'Tornado', 'Windstorm'];
}
}
:markdown
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: `
&lt;h1>{{title}}&lt;/h1>
&lt;h2>My favorite hero is: {{myHero}}&lt;/h2>
&lt;p>Heroes:&lt;/p>
&lt;ul>
&lt;li *ng-for="#hero of heroes">
{{ hero }}
&lt;/li>
&lt;/ul>
`
: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:
code-example(format="linenums" language="html").
@View({
template: `
&lt;h1>{{title}}&lt;/h1>
&lt;h2>My favorite hero is: {{myHero}}&lt;/h2>
&lt;p>Heroes:&lt;/p>
&lt;ul>
&lt;li *ng-for="#hero of heroes">
{{ hero }}
&lt;/li>
&lt;/ul>
`,
directives: [NgFor]
})
:markdown
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").
&lt;li *ng-for="#hero of heroes">
{{ hero }}
&lt;/li>
: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 doesnt follow best practices. We should separate the concerns by having another class serve the role of model and use it in the component.
Well 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: `
&lt;h1>{{title}}&lt;/h1>
&lt;h2>My favorite hero is: {{myHero.name}}&lt;/h2>
&lt;p>Heroes:&lt;/p>
&lt;ul>
&lt;li *ng-for="#hero of heroes">
{{ hero.name }}
&lt;/li>
&lt;/ul>
`,
directives: [NgFor]
})
p.
You've just defined a component that encompasses a view and controller for the app. The view
defines a template:
:markdown
The application should work as before, but it now uses the Hero class to define the hero properties.
code-example(language="html" escape="html").
<p>My name: {{ myName }}</p>
## Conditionally displaying data with NgIf
p.
Angular will automatically pull the value of <code>myName</code> and insert it into the browser and
update it whenever it changes without work on your part.
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.
p.
One thing to notice here is that though you've written your <code>DisplayComponent</code> class, you haven't
called new to create one anywhere. By associating your class with elements named 'display' in
the DOM, Angular knows to automatically call new on <code>DisplayComponent</code> and bind its properties to
that part of the template.
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 wont be added to the DOM and no message appears.
p.
When you're building templates, data bindings like these have access to the same scope of
properties as your controller class does. Here, your class is the <code>DisplayComponent</code> that has
just one property, myName.
As with the NgFor, well 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.
.callout.is-helpful
header Note
p.
While you've used <code>template:</code> to specify an inline view, for larger templates you'd
want to move them to a separate file and load them with <code>templateUrl:</code> instead.
## Using the CORE_DIRECTIVES Constant
.l-main-section
h2#Create-an-array Create an array property and use NgFor on the view
p Moving up from a single property, create an array to display as a list.
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.
code-tabs
code-pane(language="javascript" name="TypeScript" format="linenums").
//Typescript
class DisplayComponent {
myName: string;
<span class='otl'>names: Array&lt;string&gt;;</span>
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.
constructor() {
this.myName = "Alice";
<span class='otl'>this.names = ["Aarav", "Martín", "Shannon", "Ariana", "Kai"];</span>
}
}
## Summary
code-pane(language="javascript" name="Javascript (ES5)" format="linenums").
//ES5
function DisplayComponent() {
this.myName = "Alice";
<span class='otl'>this.names = ["Aarav", "Martín", "Shannon", "Ariana", "Kai"];</span>
}
p.
You can then use this array in your template with the <code>NgFor</code> directive to create copies of DOM elements
with one for each item in the array.
- 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.
code-tabs
code-pane(language="javascript" name="TypeScript" format="linenums").
//Typescript
template: `
&lt;p&gt;My name: {{ myName }}&lt;/p&gt;
&lt;p&gt;Friends:&lt;/p&gt;
&lt;ul&gt;
&lt;li *ng-for=&quot;#name of names&quot;&gt;
{{ name }}
&lt;/li&gt;
&lt;/ul&gt;
`,
code-pane(language="javascript" name="ES5" format="linenums").
//ES5
template:
&#39;&lt;p&gt;My name: {{ myName }}&lt;/p&gt;&#39; +
&#39;&lt;p&gt;Friends:&lt;/p&gt;&#39; +
&#39;&lt;ul&gt;&#39; +
&#39;&lt;li *ng-for=&quot;#name of names&quot;&gt;&#39; +
&#39;{{ name }}&#39; +
&#39;&lt;/li&gt;&#39; +
&#39;&lt;/ul&gt;&#39;,
Use these techniques any time you need to display data in the view.
p.
To make this work, you'll also need to add the <code>NgFor</code> directive used by the template so
that Angular knows to include it:
The resulting app.ts file is as follows:
code-tabs
code-pane(language="javascript" name="TypeScript" format="linenums").
//Typescript
import {Component, View, bootstrap, NgFor} from 'angular2/angular2';
@View({
...
directives: [NgFor]
})
code-example(format="linenums" language="html").
import {Component, View, bootstrap, CORE_DIRECTIVES} from 'angular2/angular2';
@Component({
selector: 'my-app'
})
@View({
template: `
&lt;h1>{{title}}&lt;/h1>
&lt;h2>My favorite hero is: {{myHero.name}}&lt;/h2>
&lt;p>Heroes:&lt;/p>
&lt;ul>
&lt;li *ng-for="#hero of heroes">
{{ hero.name }}
&lt;/li>
&lt;/ul>
&lt;p *ng-if="heroes.length > 3">There are many heroes!&lt;/p>
`,
directives: [CORE_DIRECTIVES]
})
code-pane(language="javascript" name="ES5" format="linenums").
//ES5
DisplayComponent.annotations = [
...
new angular.ViewAnnotation({
...
directives: [angular.NgFor]
})
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": 13, "name": "Bombasto" },
{ "id": 15, "name": "Magneta" },
{ "id": 20, "name": "Tornado" }
];
}
}
bootstrap(AppComponent);
p Reload and you've got your list of friends!
p.
Angular will mirror changes you make to this list over in the DOM. Add a new item and it appears in your
list. Delete one and Angular deletes the &lt;li&gt;. Reorder items and Angular makes the corresponding reorder of
the DOM list.
p Let's look at the few lines that do the work again:
code-example(language="html" format="linenums").
//HTML
&lt;li *ng-for=&quot;#name of names&quot;&gt;
{{ name }}
&lt;/li&gt;
p The way to read this is:
ul
li.
<code>*ng-for</code> : create a DOM element for each item in an
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">iterable</a>
like an array
li <code>#name</code> : refer to individual values of the iterable as 'name'
li <code>of names</code> : the iterable to use is called 'names' in the current controller
p Using this syntax, you can build UI lists from any iterable object.
.l-main-section
h2#Create-a-class Create a class for the array property and inject into component
class Hero {
id: number;
name: string;
}
p.
Before we get too much further, we should mention that putting our model (array) directly in our controller isn't
proper form. We should separate the concerns by having another class serve the role of model and inject it into
the controller.
p Make a <code>FriendsService</code> class to provide the model with the list of friends.
code-tabs
code-pane(language="javascript" name="TypeScript" format="linenums").
class FriendsService {
names: Array&lt;string&gt;;
constructor() {
this.names = ["Alice", "Aarav", "Martín", "Shannon", "Ariana", "Kai"];
}
}
code-pane(language="javascript" name="ES5" format="linenums").
function FriendsService() {
this.names = ["Aarav", "Martín", "Shannon", "Ariana", "Kai"];
}
p.
Now replace the current list of friends in DisplayComponent by including the FriendsService in the injectables list,
then including the service in the constructor, and finally setting the list of
names in DisplayComponent to the names provided by the service you passed in.
.callout.is-helpful
header ES5 Note
p.
The dependency injection syntax here is using the low-level API and is...well...not very nice. We're
working on sugaring the syntax to match the way it works in Angular 1. Expect this to change soon.
code-tabs
code-pane(language="javascript" name="TypeScript" format="linenums").
@Component({
...
<span class='otl'>appInjector: [FriendsService]</span>
})
class DisplayComponent {
myName: string;
names: Array&lt;string&gt;;
constructor(<span class='otl'>friendsService: FriendsService</span>) {
this.myName = 'Alice';
<span class='otl'>this.names = friendsService.names;</span>
}
}
code-pane(language="javascript" name="ES5" format="linenums").
//ES5
function DisplayComponent(<span class='otl'>friends</span>) {
this.myName = "Alice";
this.names = <span class='otl'>friends.names</span>;
}
DisplayComponent.annotations = [
new angular.ComponentAnnotation({
selector: "display",
<span class='otl'>appInjector: [FriendsService]</span>
}),
new angular.ViewAnnotation({
template: '{{ myName }} &lt;ul&gt; &lt;li *for="#name of names"&gt;{{ name }}&lt;/li&gt; &lt;/ul&gt;',
directives: [angular.NgFor]
})
];
<span class='otl'>DisplayComponent.parameters = [[FriendsService]];</span>
document.addEventListener("DOMContentLoaded", function() {
angular.bootstrap(DisplayComponent);
});
.l-main-section
h2#Conditionally-displaying-data-with-NgIf Conditionally displaying data with NgIf
p.
Lastly, before we move on, let's handle showing parts of our UI conditionally with <code>NgIf</code>. The
<code>NgIf</code> directive adds or removes elements from the DOM based on the expression you provide.
p See it in action by adding a paragraph at the end of your template
pre.prettyprint.lang-html
code.
&lt;p *ng-if=&quot;names.length &gt; 3&quot;&gt;You have many friends!&lt;/p&gt;
p You'll also need to add the <code>NgIf</code> directive so Angular knows to include it.
code-tabs
code-pane(language="javascript" name="TypeScript" format="linenums").
//Typescript
import {Component, View, bootstrap, NgFor, NgIf} from 'angular2/angular2';
...
directives: [NgFor, NgIf]
code-pane(language="javascript" name="ES5" format="linenums").
//ES5
directives: [angular.NgFor, angular.NgIf]
p.
As there are currently 6 items in the list, you'll see the message congratulating you on your many friends.
Remove three items from the list, reload your browser, and see that the message no longer displays.
code-tabs
code-pane(language="javascript" name="TypeScript" format="linenums").
//TypeScript
import {Component, View, bootstrap, NgFor, NgIf} from 'angular2/angular2';
...
@View({
<span class='otl'>template</span>: `
&lt;p&gt;My name: {{ myName }}&lt;/p&gt;
&lt;p&gt;Friends:&lt;/p&gt;
&lt;ul&gt;
&lt;li *ng-for=&quot;#name of names&quot;&gt;
{{ name }}
&lt;/li&gt;
&lt;/ul&gt;
&lt;p *ng-if=&quot;names.length &gt; 3&quot;&gt;You have many friends!&lt;/p&gt;
`,
directives: [NgFor, NgIf]
})
class DisplayComponent {
...
}
class FriendsService {
names: Array&lt;string&gt;;
constructor() {
<span class='otl'>this.names = ["Aarav", "Martín", "Shannon"];</span>
}
}
code-pane(language="javascript" name="ES5" format="linenums").
//ES5
function DisplayComponent(friends) {
this.myName = "Alice";
this.names = friends.names;
}
DisplayComponent.annotations = [
...
new angular.ViewAnnotation({
<span class='otl'>template</span>: '
&#39;&lt;p&gt;My name: {{ myName }}&lt;/p&gt;&#39; +
&#39;&lt;p&gt;Friends:&lt;/p&gt;&#39; +
&#39;&lt;ul&gt;&#39; +
&#39;&lt;li *ng-for=&quot;#name of names&quot;&gt;&#39; +
&#39;{{ name }}&#39; +
&#39;&lt;/li&gt;&#39; +
&#39;&lt;/ul&gt;&#39; +
&#39;&lt;p *ng-if=&quot;names.length &gt; 3&quot;&gt;You have many friends!&lt;/p&gt;&#39;',
directives: [angular.NgFor, angular.NgIf]
})
];
function FriendsService () {
<span class='otl'>this.names = ["Aarav", "Martín", "Shannon"];</span>
}
:markdown
In addition to displaying data, most applications also need to obtain data from the user. Next up, check out how to respond to user input.

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB