總的來說就是利用插值表達(dá)式和其它形式的屬性綁定機制,把數(shù)據(jù)顯示到 UI 上
a.插值表達(dá)式
要顯示組件的屬性,最簡單的方式就是通過插值表達(dá)式 (Interpolation) 來綁定屬性名。 要使用插值表達(dá)式,就把屬性名包裹在雙重花括號里放進(jìn)視圖模板,如 {{myHero}} 。
在原來的app/app.component.ts文件中修改成:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<h2>My favorite hero is: {{myHero}}</h2>
`
})
export class AppComponent {
title = 'Tour of Heroes';
myHero = 'Windstorm';
}
就會把{{title}}和{{myHero}}這兩個值輸入到模板中。
Angular 在 index.html 中查找一個 <my-app> 元素, 然后實例化一個 AppComponent,并將其渲染到 <my-app> 標(biāo)簽中。
(1)內(nèi)聯(lián) (inline) 模板還是模板文件
內(nèi)聯(lián)模板: 用template屬性;
內(nèi)聯(lián)模板文件:可以把模板定義在一個獨立的 HTML 文件中,并且通過在 @Component 裝飾器中的 templateUrl 屬性把它鏈接到組件。
習(xí)慣用內(nèi)聯(lián)模板。
(2)初始化:使用構(gòu)造函數(shù)還是變量
構(gòu)造函數(shù)初始化:把賦值操作放到constructor構(gòu)造函數(shù)中
<pre>export class AppCtorComponent {
title: string;
myHero: string;
constructor() {
this.title = 'Tour of Heroes';
this.myHero = 'Windstorm';
}
}</pre>變量賦值:title '賦值Tour of Heroes
<pre>export class AppComponent {
title = 'Tour of Heroes';
myHero = 'Windstorm';
}</pre>
(3)使用 ngFor 顯示數(shù)組屬性
先把數(shù)組列出來,*ngFor加在標(biāo)簽上,進(jìn)行迭代,每次迭代都會把屬性設(shè)置為當(dāng)前條目。
app/app.component.ts (class)
<pre>export class AppComponent {
title = 'Tour of Heroes';
heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
myHero = this.heroes[0];
}</pre>
app/app.component.ts (template)
ngFor雙引號表達(dá)式中的 hero 。 它是一個 <b>模板輸入變量 </b>( 譯注:即 ngFor 模板中從外界輸入的變量 ) 。

(4)為數(shù)據(jù)創(chuàng)建一個類
先定義一個類,
在app下創(chuàng)建一個新文件hero.ts
export class Hero {
constructor(
public id: number,
public name: string) { }
}這行代碼表示創(chuàng)建了一個hero類,類中有構(gòu)造函數(shù)和2個屬性id、name, TypeScript 提供的簡寫形式--用構(gòu)造函數(shù)的參數(shù)直接定義屬性。
這種簡寫語法:
- 定義了一個構(gòu)造函數(shù)參數(shù)及其類型
- 定義了一個同名的公開屬性
- 當(dāng)我們 new 出該類的一個實例時,把該屬性初始化為相應(yīng)的參數(shù)值
(5)使用 Hero 類
我們讓組件中的 heroes屬性返回這些 Hero 對象的數(shù)組。
app/app.component.ts (heroes)
<pre>heroes = [
new Hero(1, 'Windstorm'),
new Hero(13, 'Bombasto'),
new Hero(15, 'Magneta'),
new Hero(20, 'Tornado')
];
myHero = this.heroes[0];
</pre>
模板文件進(jìn)行更新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>
`
注意點:應(yīng)該在模板中引入hero類
(6)通過 NgIf 進(jìn)行條件顯示
應(yīng)用只需要在特定情況下顯示視圖或視圖的一部分.
Angular 的 NgIf 指令會基于條件的真假來添加或移除一個元素而不是顯隱dom。
例子:
<pre><p ngIf="heroes.length > 3">There are many heroes!</p></pre>
這個heroes數(shù)組的長度大于3就顯示p標(biāo)簽要不移除
##這節(jié)結(jié)束了 請點個贊吧——_——*