接着上一篇文章,今天跟随官网上的例子学习怎样把我们的应用分成多个组件.
首先启动我们上一章的应用
npm start
随着程序越来越大,组件越来越多时,我们不可能把所有东西都放到一个文件中,所以我们需要划分我们的功能模块.
在app下新建一个hero-detail.component.ts文件.
import {Component} from 'angular2/core';
@Component({
selector: 'my-hero-detail',
})
export class HeroDetailComponent {
}
从文件名知道.我们这个组件用来放置详细信息,我们把AppComponent模板中相关的代码剪切出来放到这个详情组件下面.
template: `
<div *ngIf="hero">
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name"/>
</div>
</div>
`
增加一个hero属性
export class HeroDetailComponent {
public hero:Hero;
}
这时我们会得到一个错误,原因是Hero类我们没有引入.所以我们同样需要把Hero类从AppComponent中拿出来
新建一个hero.ts
export interface Hero {
id: number;
name: string;
}
并且我们需要在app.component.ts和hero-detail.component.ts中使用
import {Hero} from './hero.ts';
引入这个接口
AppComponent将调用HeroDetailComponent组件来显示详细信息,所以我们需要从AppComponent中把HeroDetailComponent所需的hero变量进行传入.
<my-hero-detail [hero]="selectedHero"></my-hero-detail>
传入的hero变量需要在HeroDetailComponent中进行处理.所以我们在@Component注解中新增一个属性inputs来接收传过来的hero变量.
inputs: ['hero']
或者在类的属性前增加一个@Input注解来接收变量.
import {Component, Input} from 'angular2/core';
...
...
@Input('hero') public hero:Hero;
反回AppComponent我们引入HeroDetailComponent组件
import {HeroDetailComponent} from './hero-detail.component';
引入后我们需要告诉Angular我们将要使用这个组件.
所以我们需要在@Component中加入一个新的属性directives告诉Anguler现在要使用它.
directives: [HeroDetailComponent]
现在刷新页面后我们会看到和上一章同样的效果.
目录结构:
angular2-tour-of-heroes
|__node_modules
|__app
|__app.component.ts
|__boot.ts
|__hero.ts
|__hero-detail.component.ts
|__index.html
|__package.json
|__tsconfig.json
本文指导如何在Angular应用中实现组件化,通过实例演示创建、导入、使用组件,并解决引入和传参问题。
139

被折叠的 条评论
为什么被折叠?



