看个具体的例子:
我有一个风格为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的原创文章,请关注公众号"汪子熙":