Angular 父子Component的数据绑定实现
生活随笔
收集整理的這篇文章主要介紹了
Angular 父子Component的数据绑定实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
看個具體的例子:
我有一個風格為Master Detail的Angular應用。下圖紅色高亮區域包含了一個hero detail Component,即下圖藍色高亮區域所示。
這兩個Component的selector可以在Chrome開發者工具的element標簽頁里看到:
具體實現步驟:
(1) 在app.module.ts里導入app-heroes和app-hero-detail這兩個selector對應的Component,并在NgModule里聲明:
(2) 在hero detail Component里定義一個Hero屬性,使用裝飾器@Input修飾,告知Angular,當其他Component嵌入該Component時,需要將值綁定到這個輸入屬性上。
detail Component的html沒有特殊之處,顯示屬性hero對應的字段:
(3) parent Component,即消費這個detail Component的hero Component,將當前li里選中的hero實例綁定給detail Component使用@Input修飾的屬性hero:
<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>
如果移除掉detail Component里的@Input修飾器,
會出現編譯錯誤:
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的Angular 父子Component的数据绑定实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 亚马逊云业务和 HR 部门裁员,内部信公
- 下一篇: 首发9999元 惠普暗影精灵9 SLIM