創立hero-detail元件
在前一篇新手教程3-使用angular的迴圈及判斷式等功能裡,我們在顯示selectedHero的資訊時是與列表寫在同一個頁面
但如果顯示詳細資訊的地方有需要額外拆分出來,可以在創立一個元件,並將selectedHero傳入元件
1 | ng generate component hero-detail |
寫入hero-detail的內容
開啟檔案src/app/hero-detail/hero-detail.component.html,這邊會將selectedHero的名稱改為hero
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 | < div * ngIf = "hero" > < h2 >{{ hero.name | uppercase }} Details</ h2 > < div >< span >id: </ span >{{hero.id}}</ div > < div > < label >name: < input [(ngModel)]="hero.name" placeholder = "name" /> </ label > </ div > </ div > |
讓元件能接受外部傳送物件進來
開啟src/app/hero-detail/hero-detail.component.ts
1 | import { Hero } from '../hero' ; |
在hero-detail.component.ts裡面,hero一定要以@Input來宣告這個物件
1 | @Input() hero: Hero; |
而在HeroesComponent裡,則會以下面的宣告來將hero的值傳入
1 | < app-hero-detail [hero]="selectedHero"></ app-hero-detail > |
現在我們打開heroes.component.html,修改後的網頁內容會如下
01 02 03 04 05 06 07 08 09 10 11 12 13 14 | < h2 >My Heroes</ h2 > < ul class = "heroes" > < li * ngFor = "let hero of heroes" [class.selected]="hero === selectedHero" (click)="onSelect(hero)"> < span class = "badge" >{{hero.id}}</ span > {{hero.name}} </ li > </ ul > < app-hero-detail [hero]="selectedHero"></ app-hero-detail > |
今日練習的範例連結:live example / download example