組件是通過導入和使用它們作爲一個正常的HTML標記的父組件,結帳下面的例子對參考。
my-app組件通過導入命令導入並直接使用它,從而引用HeroDetailComponent。
兩個重要線是
進口
import {HeroDetailComponent} from './hero-detail.component';
部件的通過直接添加標籤到分量模板的使用
<my-hero-detail [hero]="selectedHero"></my-hero-detail>
import {Component} from 'angular2/core';
import {Hero} from './hero';
import {HeroDetailComponent} from './hero-detail.component';
@Component({
selector: 'my-app',
template:`
<h1>{{title}}</h1>
<h2>My Heroes</h2>
<ul class="heroes">
<li *ngFor="#hero of heroes"
[class.selected]="hero === selectedHero"
(click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>
<my-hero-detail [hero]="selectedHero"></my-hero-detail>
`,
directives: [HeroDetailComponent]
})
export class AppComponent {
public title = 'Tour of Heroes';
public heroes = HEROES;
public selectedHero: Hero;
onSelect(hero: Hero) { this.selectedHero = hero; }
}
英雄細節組件外觀像這樣,
import {Component} from 'angular2/core';
import {Hero} from './hero';
@Component({
selector: 'my-hero-detail',
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>
`,
inputs: ['hero']
})
export class HeroDetailComponent {
public hero: Hero;
}
Plunkr Link
https://angular.io/docs/ts/latest/api/core/Query-var.html – TGH