iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 5
0
自我挑戰組

Angular 學習雜記系列 第 5

Angular 學習雜記-Angular簡單範例

我們建立一個員工列表的範例好了,開始之前建立的HiAngular專案,首先來說明一下,建立一個component,就會產生出四個檔案,如下說明:

https://ithelp.ithome.com.tw/upload/images/20190921/20000953oSgBYOdEHo.png

app-component.ts程式碼如下:

https://ithelp.ithome.com.tw/upload/images/20190921/20000953lsEBHdmAIB.png

詳細的說明,可以參考官方網站中文化的說明,請參考https://angular.tw/start ,我們是要做,依我們自己的理解的說明,來做重點的整理。
首先,先建立出員工資料來源的陣列資料。在app目錄,選取子視窗,選取「New File」,直接輸入「employeelist.ts」,注意的是,連副檔名,都要輸入。如下圖所示:

https://ithelp.ithome.com.tw/upload/images/20190921/200009534Cwh9NUacF.png

在employeelist.ts,輸入下述程式碼,建立員工的資料陣列。

export const employeelist = [
    {
      serialnumber: 'W01',
      name: '張三',
      address: '台北市內湖區'
    },
    {
      serialnumber: 'W02',
      name: '李四',
      address: '台北市信義區'
    },
    {
      serialnumber: 'W03',
      name: '王五',
      address: ''
    }
];

在app-component.ts,先用import資料來源。再指定變數,來取得資料來源的物件資料。

import { Component } from '@angular/core';

// 載入資料來源。
import { employeelist } from './employeelist';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  // 變數employeelists取得資料來源。
  employeelists = employeelist;
}

最後,再app-component.html,使用ngFor結構,帶出員工資料的列表,使用ngIf來判斷資料值是否為空白,如果不是空白,才要顯示等基本的用法。

<table>
  <thead>
    <tr>
      <th>順序</th>
      <th>員工編號</th>
      <th>姓名</th>
      <th>地址</th>
    </tr>
  </thead>
  <tbody>
      <tr *ngFor="let employee of employeelists; index as i">
      <td>{{i + 1}}</td>
      <td>{{employee.serialnumber}}</td>
      <td>{{employee.name}}</td>
      <td>
        <p *ngIf="employee.address.trim() !== ''">
          {{employee.address}}
        </p>
      </td>
    </tr>
  </tbody>
</table>

<router-outlet></router-outlet>

執行的畫面,如下:

https://ithelp.ithome.com.tw/upload/images/20190921/20000953PBXfJYrPMl.png

後續,再細部說明用法。


上一篇
Angular 學習雜記-Angular資料夾、檔案說明
下一篇
Angular 學習雜記-Angular程式指令說明
系列文
Angular 學習雜記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言