Angular-第3課-與HTML元件互動

Vincent Zheng
新手工程師的程式教室
6 min readNov 18, 2018

第2課在html檔顯示了ts檔中的字串內容。這一課我們會在網頁中加入文字輸入框,體會Angular的「雙向綁定」特性。接著再加入清單,顯示多個hero物件。

課程關鍵字:#輸入框 #清單 #陣列 #迴圈 #雙向綁定

一、文字輸入框

現在我們要在html檔中加入一個文字輸入框,用來編輯hero的名字。首先將 heroes.component.html下方原本顯示名字文字的地方改為如下:

<div>
<label>name:
<input [(ngModel)]="hero.name" placeholder="name">
</label>
</div>

這樣就加入了一個輸入框(<input>標籤)。placeholder是HTML自己的屬性,在輸入框空白時會出現作為提示文字,類似Android的hint。至於「[(ngModel)]」則是Angular的「雙向綁定」語法,下面會再講解。

這是我們在專案中第一次使用[(ngModel)],但它是Angular的屬性,不像HTML可以寫了直接用,因此仍需要進行匯入。

請開啟/src/app/app.module.ts,在上方匯入表單函式庫FormsModule。而下方的@NgModule標記,裡面有個「imports」陣列,接著將FormsModule添加到該陣列。如此就能在專案中各個html檔裡使用[(ngModel)]了。

匯入FormsModule
加入文字輸入框的網頁

如果去編輯文字輸入框的內容,會發現上面Detail那裡的字立刻跟著改變,這就是前面提到「雙向綁定」的特性。HeroComponent載入時,會將ts檔的hero.name屬性填入到html檔的輸入框中,這是單向。
編輯時,新輸入的資料會回流到ts檔中的hero物件,這是雙向。後續由於插值綁定的效果,新的hero.name又被插進html檔,所以Detail才會同步改變。

雙向綁定使得文字能同步改變

二、清單

這一節我們要製作清單,用來顯示很多個hero。首先在/src/app目錄建立「mock-heroes.ts」,它是一個常數陣列,存放很多hero物件,內容如下:

import { Hero } from './hero';export const HEROES: Hero[] = [
{ id: 11, name: 'Mr. Nice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' }
];

接著仿照第2課的做法,在heroes.component.ts宣告「heroes」,存放剛剛的陣列,別忘了要從外部匯入。這時hero已經不需要了,可以刪除。

從外部定義好的ts檔匯入陣列

程式檔準備完畢後,請開啟heroes.component.html,將內容改為如下:

<h2>My Heroes</h2>
<ul class="heroes">
<li *ngFor="let hero of heroes">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>

<ul>和<li>都是HTML的標籤,前者代表一個清單,後者則是清單中的小項目。在<li>標籤中,有個「*ngFor」屬性,這是Angular的迴圈語法。
它的值「let hero of heroes」,意思是從ts檔中的heroes陣列逐一取出元素,且取名為hero。它就像Java的enhance for迴圈。

迴圈在循環時,會不斷地顯示<li>與</li>之間的內容。所以每次當不同的hero元素被取出,就能將這些hero的屬性值一個個列出來。

此時網頁已經能看見清單,但只是純文字。因此在heroes.component.css中貼上官方文件的範例CSS內容。

/* HeroesComponent's private CSS styles */
.selected {
background-color: #CFD8DC !important;
color: white;
}
.heroes {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 15em;
}
.heroes li {
cursor: pointer;
position: relative;
left: 0;
background-color: #EEE;
margin: .5em;
padding: .3em 0;
height: 1.6em;
border-radius: 4px;
}
.heroes li.selected:hover {
background-color: #BBD8DC !important;
color: white;
}
.heroes li:hover {
color: #607D8B;
background-color: #DDD;
left: .1em;
}
.heroes .text {
position: relative;
top: -3px;
}
.heroes .badge {
display: inline-block;
font-size: small;
color: white;
padding: 0.8em 0.7em 0 0.7em;
background-color: #607D8B;
line-height: 1em;
position: relative;
left: -1px;
top: -4px;
height: 1.8em;
margin-right: .8em;
border-radius: 4px 0 0 4px;
}

儲存後重新整理網頁,html檔在載入時,透過迴圈語法,將ts檔中的heroes陣列內容給列出來。再加上css檔定義的風格,一個漂亮的清單就出現了。滑鼠經過清單項目時還會有樣式的變化。

使用迴圈列出陣列元素

--

--

Vincent Zheng
新手工程師的程式教室

我是Vincent,是個來自資管系的後端軟體工程師。當初因為學校作業,才踏出寫部落格的第一步。這裡提供程式教學文章,包含自學和工作上用到的經驗,希望能讓讀者學到東西。我的部落已搬家至 https://chikuwa-tech-study.blogspot.com/