显示数据

Displaying Data

在 Angular 中最典型的数据显示方式,就是把 HTML 模板中的控件绑定到 Angular 组件的属性。

You can display data by binding controls in an HTML template to properties of an Angular component.

本章中,你将创建一个带英雄列表的组件。 你将显示英雄名字的列表,并根据条件在列表下方显示一条消息。

In this page, you'll create a component with a list of heroes. You'll display the list of hero names and conditionally show a message below the list.

最终的用户界面是这样的:

The final UI looks like this:

Final UI

这个在线例子 / 下载范例演示了本章中描述的所有语法和代码片段。

The在线例子 / 下载范例demonstrates all of the syntax and code snippets described in this page.

使用插值表达式显示组件属性

Showing component properties with interpolation

要显示组件的属性,最简单的方式就是通过插值表达式 (interpolation) 来绑定属性名。 要使用插值表达式,就把属性名包裹在双花括号里放进视图模板,如 {{myHero}}

The easiest way to display 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}}.

按照快速起步的说明,创建一个新项目,名为displaying-data

Follow the Getting Started instructions for creating a new project named displaying-data.

删除 app.component.html 文件,这个范例中不再需要它了。

Delete the app.component.html file. It is not needed for this example.

然后,到 app.component.ts 文件中修改组件的模板和代码。

Then modify the app.component.ts file by changing the template and the body of the component.

修改完之后,它应该是这样的:

When you're done, it should look like this:

import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <h1>{{title}}</h1> <h2>My favorite hero is: {{myHero}}</h2> ` }) export class AppComponent { title = 'Tour of Heroes'; myHero = 'Windstorm'; }
src/app/app.component.ts
      
      
  1. import { Component } from '@angular/core';
  2.  
  3. @Component({
  4. selector: 'app-root',
  5. template: `
  6. <h1>{{title}}</h1>
  7. <h2>My favorite hero is: {{myHero}}</h2>
  8. `
  9. })
  10. export class AppComponent {
  11. title = 'Tour of Heroes';
  12. myHero = 'Windstorm';
  13. }

再把两个属性 titlemyHero 添加到之前空白的组件中。

You added two properties to the formerly empty component: title and myHero.

修改完的模板会使用双花括号形式的插值表达式来显示这两个模板属性:

The template displays the two component properties using double curly brace interpolation:

template: ` <h1>{{title}}</h1> <h2>My favorite hero is: {{myHero}}</h2> `
src/app/app.component.ts (template)
      
      template: `
  <h1>{{title}}</h1>
  <h2>My favorite hero is: {{myHero}}</h2>
  `
    

模板是包在 ECMAScript 2015 反引号 (`) 中的一个多行字符串。 反引号 (`) — 注意,不是单引号 (') — 允许把一个字符串写在多行上, 使 HTML 模板更容易阅读。

The template is a multi-line string within ECMAScript 2015 backticks (`). The backtick (`)—which is not the same character as a single quote (')—allows you to compose a string over several lines, which makes the HTML more readable.

Angular 自动从组件中提取 titlemyHero 属性的值,并且把这些值插入浏览器中。当这些属性发生变化时,Angular 就会自动刷新显示。

Angular automatically pulls the value of the title and myHero properties from the component and inserts those values into the browser. Angular updates the display when these properties change.

严格来说,“重新显示”是在某些与视图有关的异步事件之后发生的,例如,按键、定时器完成或对 HTTP 请求的响应。

More precisely, the redisplay occurs after some kind of asynchronous event related to the view, such as a keystroke, a timer completion, or a response to an HTTP request.

注意,你没有调用 new 来创建 AppComponent 类的实例,是 Angular 替你创建了它。那么它是如何创建的呢?

Notice that you don't call new to create an instance of the AppComponent class. Angular is creating an instance for you. How?

注意 @Component 装饰器中指定的 CSS 选择器 selector,它指定了一个叫 <app-root> 的元素。 该元素是 index.html 文件里的一个占位符。

The CSS selector in the @Component decorator specifies an element named <app-root>. That element is a placeholder in the body of your index.html file:

<body> <app-root></app-root> </body>
src/index.html (body)
      
      <body>
  <app-root></app-root>
</body>
    

当你通过 main.ts 中的 AppComponent 类启动时,Angular 在 index.html 中查找一个 <app-root> 元素, 然后实例化一个 AppComponent,并将其渲染到 <app-root> 标签中。

When you bootstrap with the AppComponent class (in main.ts), Angular looks for a <app-root> in the index.html, finds it, instantiates an instance of AppComponent, and renders it inside the <app-root> tag.

运行应用。它应该显示出标题和英雄名:

Now run the app. It should display the title and hero name:

Title and Hero

回顾一下前面所做的决定,看看还有哪些其它选择。

The next few sections review some of the coding choices in the app.

内联 (inline) 模板还是模板文件?

Template inline or template file?

你可以在两种地方存放组件模板。 你可以使用 template 属性把它定义为内联的,或者把模板定义在一个独立的 HTML 文件中, 再通过 @Component 装饰器中的 templateUrl 属性, 在组件元数据中把它链接到组件。

You can store your component's template in one of two places. You can define it inline using the template property, or you can define the template in a separate HTML file and link to it in the component metadata using the @Component decorator's templateUrl property.

到底选择内联 HTML 还是独立 HTML 取决于个人喜好、具体状况和组织级策略。 上面的应用选择内联 HTML ,是因为模板很小,而且没有额外的 HTML 文件显得这个演示简单些。

The choice between inline and separate HTML is a matter of taste, circumstances, and organization policy. Here the app uses inline HTML because the template is small and the demo is simpler without the additional HTML file.

无论用哪种风格,模板数据绑定在访问组件属性方面都是完全一样的。

In either style, the template data bindings have the same access to the component's properties.

默认情况下,Angular CLI 命令 ng generate component在生成组件时会带有模板文件,你可以通过参数来覆盖它:

By default, the Angular CLI command ng generate componentgenerates components with a template file. You can override that with:

ng generate component hero -it
      
      ng generate component hero -it
    

使用构造函数还是变量初始化?

Constructor or variable initialization?

虽然这个例子使用了变量赋值的方式初始化组件,你还可以使用构造函数来声明和初始化属性。

Although this example uses variable assignment to initialize the components, you could instead declare and initialize the properties using a constructor:

export class AppCtorComponent { title: string; myHero: string; constructor() { this.title = 'Tour of Heroes'; this.myHero = 'Windstorm'; } }
      
      export class AppCtorComponent {
  title: string;
  myHero: string;

  constructor() {
    this.title = 'Tour of Heroes';
    this.myHero = 'Windstorm';
  }
}
    

为了让本应用更加简短,它采用了更简单的“变量赋值”风格。

This app uses more terse "variable assignment" style simply for brevity.

使用 ngFor 显示数组属性

Showing an array property with *ngFor

要显示一个英雄列表,先向组件中添加一个英雄名字数组,然后把 myHero 重定义为数组中的第一个名字。

To display a list of heroes, begin by adding an array of hero names to the component and redefine myHero to be the first name in the array.

export class AppComponent { title = 'Tour of Heroes'; heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado']; myHero = this.heroes[0]; }
src/app/app.component.ts (class)
      
      export class AppComponent {
  title = 'Tour of Heroes';
  heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
  myHero = this.heroes[0];
}
    

接着,在模板中使用 Angular 的 ngFor 指令来显示 heroes 列表中的每一项。

Now use the Angular ngFor directive in the template to display each item in the heroes list.

template: ` <h1>{{title}}</h1> <h2>My favorite hero is: {{myHero}}</h2> <p>Heroes:</p> <ul> <li *ngFor="let hero of heroes"> {{ hero }} </li> </ul> `
src/app/app.component.ts (template)
      
      template: `
  <h1>{{title}}</h1>
  <h2>My favorite hero is: {{myHero}}</h2>
  <p>Heroes:</p>
  <ul>
    <li *ngFor="let hero of heroes">
      {{ hero }}
    </li>
  </ul>
`
    

这个界面使用了由 <ul><li> 标签组成的无序列表。<li> 元素里的 *ngFor 是 Angular 的“迭代”指令。 它将 <li> 元素及其子级标记为“迭代模板”:

This UI uses the HTML unordered list with <ul> and <li> tags. The *ngFor in the <li> element is the Angular "repeater" directive. It marks that <li> element (and its children) as the "repeater template":

<li *ngFor="let hero of heroes"> {{ hero }} </li>
src/app/app.component.ts (li)
      
      <li *ngFor="let hero of heroes">
  {{ hero }}
</li>
    

不要忘记 *ngFor 中的前导星号 (*)。它是语法中不可或缺的一部分。 更多信息,见模板语法

Don't forget the leading asterisk (*) in *ngFor. It is an essential part of the syntax. For more information, see the Template Syntax page.

注意看 ngFor 双引号表达式中的 hero,它是一个模板输入变量。 更多模板输入变量的信息,见模板语法中的 微语法 (microsyntax)

Notice the hero in the ngFor double-quoted instruction; it is an example of a template input variable. Read more about template input variables in the microsyntax section of the Template Syntax page.

Angular 为列表中的每个条目复制一个 <li> 元素,在每个迭代中,把 hero 变量设置为当前条目(英雄)。 Angular 把 hero 变量作为双花括号插值表达式的上下文。

Angular duplicates the <li> for each item in the list, setting the hero variable to the item (the hero) in the current iteration. Angular uses that variable as the context for the interpolation in the double curly braces.

本例中,ngFor 用于显示一个“数组”, 但 ngFor 可以为任何可迭代的 (iterable) 对象重复渲染条目。

In this case, ngFor is displaying an array, but ngFor can repeat items for any iterable object.

现在,英雄们出现在了一个无序列表中。

Now the heroes appear in an unordered list.

After ngfor

为数据创建一个类

Creating a class for the data

应用代码直接在组件内部直接定义了数据。 作为演示还可以,但它显然不是最佳实践。

The app's code defines the data directly inside the component, which isn't best practice. In a simple demo, however, it's fine.

现在使用的是到了一个字符串数组的绑定。在真实的应用中,大多是到一个对象数组的绑定。

At the moment, the binding is to an array of strings. In real applications, most bindings are to more specialized objects.

要将此绑定转换成使用对象,需要把这个英雄名字数组变成 Hero 对象数组。但首先得有一个 Hero 类。

To convert this binding to use specialized objects, turn the array of hero names into an array of Hero objects. For that you'll need a Hero class:

ng generate class hero
      
      ng generate class hero
    

代码如下:

With the following code:

export class Hero { constructor( public id: number, public name: string) { } }
src/app/hero.ts
      
      export class Hero {
  constructor(
    public id: number,
    public name: string) { }
}
    

你定义了一个类,具有一个构造函数和两个属性:idname

You've defined a class with a constructor and two properties: id and name.

它可能看上去不像是有属性的类,但它确实有,利用的是 TypeScript 提供的简写形式 —— 用构造函数的参数直接定义属性。

It might not look like the class has properties, but it does. The declaration of the constructor parameters takes advantage of a TypeScript shortcut.

来看第一个参数:

Consider the first parameter:

public id: number,
src/app/hero.ts (id)
      
      public id: number,
    

这个简写语法做了很多:

That brief syntax does a lot:

  • 声明了一个构造函数参数及其类型。

    Declares a constructor parameter and its type.

  • 声明了一个同名的公共属性。

    Declares a public property of the same name.

  • 当创建该类的一个实例时,把该属性初始化为相应的参数值。

    Initializes that property with the corresponding argument when creating an instance of the class.

使用 Hero 类

Using the Hero class

导入了 Hero 类之后,组件的 heroes 属性就可以返回一个类型化的Hero 对象数组了。

After importing the Hero class, the AppComponent.heroes property can return a typed array of Hero objects:

heroes = [ new Hero(1, 'Windstorm'), new Hero(13, 'Bombasto'), new Hero(15, 'Magneta'), new Hero(20, 'Tornado') ]; myHero = this.heroes[0];
src/app/app.component.ts (heroes)
      
      heroes = [
  new Hero(1, 'Windstorm'),
  new Hero(13, 'Bombasto'),
  new Hero(15, 'Magneta'),
  new Hero(20, 'Tornado')
];
myHero = this.heroes[0];
    

接着,修改模板。 现在它显示的是英雄的 idname。 要修复它,只显示英雄的 name 属性就行了。

Next, update the template. At the moment it displays the hero's id and name. Fix that to display only the hero's name property.

template: ` <h1>{{title}}</h1> <h2>My favorite hero is: {{myHero.name}}</h2> <p>Heroes:</p> <ul> <li *ngFor="let hero of heroes"> {{ hero.name }} </li> </ul> `
src/app/app.component.ts (template)
      
      template: `
  <h1>{{title}}</h1>
  <h2>My favorite hero is: {{myHero.name}}</h2>
  <p>Heroes:</p>
  <ul>
    <li *ngFor="let hero of heroes">
      {{ hero.name }}
    </li>
  </ul>
`
    

显示上还和以前一样,不过代码更清晰了。

The display looks the same, but the code is clearer.

通过 NgIf 进行条件显示

Conditional display with NgIf

有时,应用需要只在特定情况下显示视图或视图的一部分。

Sometimes an app needs to display a view or a portion of a view only under specific circumstances.

来改一下这个例子,如果多于三位英雄,显示一条消息。

Let's change the example to display a message if there are more than three heroes.

Angular 的 ngIf 指令会根据一个布尔条件来显示或移除一个元素。 来看看实际效果,把下列语句加到模板的底部:

The Angular ngIf directive inserts or removes an element based on a truthy/falsy condition. To see it in action, add the following paragraph at the bottom of the template:

<p *ngIf="heroes.length > 3">There are many heroes!</p>
src/app/app.component.ts (message)
      
      <p *ngIf="heroes.length > 3">There are many heroes!</p>
    

不要忘了 *ngIf 中的前导星号 (*)。它是本语法中不可或缺的一部分。 更多 ngIf* 的内容,见模板语法中的ngIf

Don't forget the leading asterisk (*) in *ngIf. It is an essential part of the syntax. Read more about ngIf and * in the ngIf section of the Template Syntax page.

双引号中的模板表达式 *ngIf="heros.length > 3",外观和行为很象 TypeScript 。 当组件中的英雄列表有三个以上的条目时,Angular 把这个段落添加到 DOM 中,于是消息显示了出来。 更多信息,见模板语法中的模板表达式

The template expression inside the double quotes, *ngIf="heroes.length > 3", looks and behaves much like TypeScript. When the component's list of heroes has more than three items, Angular adds the paragraph to the DOM and the message appears. If there are three or fewer items, Angular omits the paragraph, so no message appears. For more information, see the template expressions section of the Template Syntax page.

Angular 并不是在显示和隐藏这条消息,它是在从 DOM 中添加和移除这个段落元素。 这会提高性能,特别是在一些大的项目中有条件地包含或排除一大堆带着很多数据绑定的 HTML 时。

Angular isn't showing and hiding the message. It is adding and removing the paragraph element from the DOM. That improves performance, especially in larger projects when conditionally including or excluding big chunks of HTML with many data bindings.

试一下。因为这个数组中有四个条目,所以消息应该显示出来。 回到 app.component.ts,从英雄数组中删除或注释掉一个元素。 浏览器应该自动刷新,消息应该会消失。

Try it out. Because the array has four items, the message should appear. Go back into app.component.ts and delete or comment out one of the elements from the hero array. The browser should refresh automatically and the message should disappear.

小结

Summary

现在你知道了如何使用:

Now you know how to use:

  • 带有双花括号的插值表达式 (interpolation) 来显示一个组件属性。

    Interpolation with double curly braces to display a component property.

  • ngFor 显示数组。

    ngFor to display an array of items.

  • 用一个 TypeScript 类来为你的组件描述模型数据并显示模型的属性。

    A TypeScript class to shape the model data for your component and display properties of that model.

  • ngIf 根据一个布尔表达式有条件地显示一段 HTML。

    ngIf to conditionally display a chunk of HTML based on a boolean expression.

下面是最终的代码:

Here's the final code:

import { Component } from '@angular/core'; import { Hero } from './hero'; @Component({ selector: 'app-root', template: ` <h1>{{title}}</h1> <h2>My favorite hero is: {{myHero.name}}</h2> <p>Heroes:</p> <ul> <li *ngFor="let hero of heroes"> {{ hero.name }} </li> </ul> <p *ngIf="heroes.length > 3">There are many heroes!</p> ` }) export class AppComponent { title = 'Tour of Heroes'; heroes = [ new Hero(1, 'Windstorm'), new Hero(13, 'Bombasto'), new Hero(15, 'Magneta'), new Hero(20, 'Tornado') ]; myHero = this.heroes[0]; }export class Hero { constructor( public id: number, public name: string) { } }import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule);
      
      
  1. import { Component } from '@angular/core';
  2.  
  3. import { Hero } from './hero';
  4.  
  5. @Component({
  6. selector: 'app-root',
  7. template: `
  8. <h1>{{title}}</h1>
  9. <h2>My favorite hero is: {{myHero.name}}</h2>
  10. <p>Heroes:</p>
  11. <ul>
  12. <li *ngFor="let hero of heroes">
  13. {{ hero.name }}
  14. </li>
  15. </ul>
  16. <p *ngIf="heroes.length > 3">There are many heroes!</p>
  17. `
  18. })
  19. export class AppComponent {
  20. title = 'Tour of Heroes';
  21. heroes = [
  22. new Hero(1, 'Windstorm'),
  23. new Hero(13, 'Bombasto'),
  24. new Hero(15, 'Magneta'),
  25. new Hero(20, 'Tornado')
  26. ];
  27. myHero = this.heroes[0];
  28. }