Posted on Leave a comment

[新手教程-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

Leave a Reply