Angular 2 數據顯示
本章節我們將為大家介紹如何將數據顯示到用戶介面上,可以使用以下三種方式:
- 通過插值運算式顯示組件的屬性
- 通過 NgFor 顯示數組型屬性
- 通過 NgIf 實現按條件顯示
通過插值運算式顯示組件的屬性
要顯示組件的屬性,插值是最簡單的方式,格式為:{{屬性名}}。
以下代碼基於 Angular 2 TypeScript 環境配置 來創建,你可以在該章節上下載源碼,並修改以下提到的幾個檔。
app/app.component.ts 檔:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<h2>我喜歡的網站: {{mySite}}</h2>
`
})
export class AppComponent {
title = '站點列表';
mySite = 'IT研修';
}
Angular 會自動從組件中提取 title 和 mySite 屬性的值,並顯示在流覽器中,顯示資訊如下:
注意:範本是包在反引號 (`) 中的一個多行字串,而不是單引號 (')。
使用 ngFor 顯示數組屬性
我們也可以迴圈輸出多個站點,修改以下檔:
app/app.component.ts 檔:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<h2>我喜歡的網站: {{mySite}}</h2>
<p>網站列表:</p>
<ul>
<li *ngFor="let site of sites">
{{ site }}
</li>
</ul>
`
})
export class AppComponent {
title = '站點列表';
sites = ['IT研修', 'Google', 'Taobao', 'Facebook'];
mySite = this.sites[0];
}
代碼中我們在範本使用 Angular 的 ngFor 指令來顯示 sites 列表中的每一個條目,不要忘記 *ngFor 中的前導星號 (*) 。。
修改後,流覽器顯示如下所示:
實例中 ngFor 迴圈了一個數組, 事實上 ngFor 可以迭代任何可迭代的對象。
接下來我們在 app 目錄下創建 site.ts 的檔,代碼如下:
app/site.ts 檔:
export class Site {
constructor(
public id: number,
public name: string) { }
}
以上代碼中定義了一個帶有構造函數和兩個屬性: id 和 name 的類。
接著我們迴圈輸出 Site 類的 name 屬性:
app/app.component.ts 檔:
import { Component } from '@angular/core';
import { Site } from './site';
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<h2>我喜歡的網站: {{mySite.name}}</h2>
<p>網站列表:</p>
<ul>
<li *ngFor="let site of sites">
{{ site.name }}
</li>
</ul>
`
})
export class AppComponent {
title = '站點列表';
sites = [
new Site(1, 'IT研修'),
new Site(2, 'Google'),
new Site(3, 'Taobao'),
new Site(4, 'Facebook')
];
mySite = this.sites[0];
}
修改後,流覽器顯示如下所示:
通過 NgIf 進行條件顯示
我們可以使用 NgIf 來設置輸出指定條件的數據。
以下實例中我們判斷如果網站數 3 個以上,輸出提示資訊:修改以下 app.component.ts 檔,代碼如下:
app/app.component.ts 檔:
import { Component } from '@angular/core';
import { Site } from './site';
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<h2>我喜歡的網站: {{mySite.name}}</h2>
<p>網站列表:</p>
<ul>
<li *ngFor="let site of sites">
{{ site.name }}
</li>
</ul>
<p *ngIf="sites.length > 3">你有很多個喜歡的網站!</p>
`
})
export class AppComponent {
title = '站點列表';
sites = [
new Site(1, 'IT研修'),
new Site(2, 'Google'),
new Site(3, 'Taobao'),
new Site(4, 'Facebook')
];
mySite = this.sites[0];
}
修改後,流覽器顯示如下所示,底部多了個提示資訊: