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}}.
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 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.
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?
When you bootstrap with the AppComponent class (in main.ts), Angular looks for a <my-app>
in the index.html, finds it, instantiates an instance of AppComponent, and renders it
inside the <my-app> tag.
运行应用。它应该显示出标题和英雄名:
Now run the app. It should display the title and hero name:
回顾一下前面所做的决定,看看还有哪些其它选择。
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.
使用构造函数还是变量初始化?
Constructor or variable initialization?
虽然这个例子使用了变量赋值的方式初始化组件,你还可以使用构造函数来声明和初始化属性。
Although this example uses variable assignment to initialize the components, you can instead declare and initialize the properties using a constructor:
src/app/app-ctor.component.ts (class)
exportclassAppCtorComponent{
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.
src/app/app.component.ts (class)
exportclassAppComponent{
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.
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>
`
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":
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 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.
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:
src/app/app.component.ts (message)
<p *ngIf="heroes.length > 3">There are many heroes!</p>
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="heros.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.
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:'my-app',
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>