iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 4
2
Modern Web

用30天深入Angular 5的世界系列 第 4

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

本文同步發佈於:Claire's BLOG

創立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 [(ngModel)]="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 [hero]="selectedHero"></app-hero-detail>

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

<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


上一篇
[新手教程-3] 使用Angular的迴圈及判斷式等功能
下一篇
[新手教程-5] 建立Service
系列文
用30天深入Angular 5的世界31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
tytom2003
iT邦新手 5 級 ‧ 2020-05-31 20:44:41

<app-hero-detail [hero]="selectedHero"> 裏的[hero]="selectedHero"是怎樣解? 為什麼hero要用[]? THX

我要留言

立即登入留言