[新手教程-4] Angular的主從元件開發

創立hero-detail元件

在前一篇新手教程3-使用angular的迴圈及判斷式等功能裡,我們在顯示selectedHero的資訊時是與列表寫在同一個頁面
但如果顯示詳細資訊的地方有需要額外拆分出來,可以在創立一個元件,並將selectedHero傳入元件

ng generate component hero-detail

寫入hero-detail的內容

開啟檔案src/app/hero-detail/hero-detail.component.html,這邊會將selectedHero的名稱改為hero


<div *ngIf="hero">

<h2>{{ hero.name | uppercase }} Details</h2>


<div><span>id: </span>{{hero.id}}</div>


<div>
    <label>name:
      <input &#91;(ngModel)&#93;="hero.name" placeholder="name"/>
    </label>
  </div>

</div>

讓元件能接受外部傳送物件進來

開啟src/app/hero-detail/hero-detail.component.ts

import { Hero } from '../hero';

在hero-detail.component.ts裡面,hero一定要以@Input來宣告這個物件

@Input() hero: Hero;

而在HeroesComponent裡,則會以下面的宣告來將hero的值傳入

<app-hero-detail &#91;hero&#93;="selectedHero"></app-hero-detail>

現在我們打開heroes.component.html,修改後的網頁內容會如下

<h2>My Heroes</h2>



<ul class="heroes">

<li *ngFor="let hero of heroes" &#91;class.selected&#93;="hero === selectedHero" (click)="onSelect(hero)">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>

</ul>


<app-hero-detail &#91;hero&#93;="selectedHero"></app-hero-detail>

今日練習的範例連結:live example / download example


17年資歷女工程師,專精於動畫、影像辨識以及即時串流程式開發。經常組織活動,邀請優秀的女性分享她們的技術專長,並在眾多場合分享自己的技術知識,也活躍於非營利組織,辦理活動來支持特殊兒及其家庭。期待用技術改變世界。