我关注Angular2基础知识的angular tutorial,尝试将其翻译为javascript,因为它目前仅适用于Typescript。
我目前有两个文件:app.component.js和hero-detail.component.js。 位于app.component.js我有我的AppComponent。由此,我想将hero-detail.component.js中的组件作为指令加载。
我当前的代码看起来像这样,但我无法弄清楚如何加载HeroDetailComponent:
app.AppComponent =
ng.core.Component({
selector: 'my-app',
inputs : ['hero'],
directives: [HeroDetailComponent],
template: `<h1>{{title}}</h1>My Heroes<h2></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>
<my-hero-detail [hero]="selectedHero"></my-hero-detail>
`
})
.Class({
constructor: function() {
this.title = 'Tour of Heroes'
this.heroes = HEROES
this.selectedHero = null
},
onSelect(hero) { this.selectedHero = hero; }
});
})(window.app || (window.app = {}));enter code here
答案 0 :(得分:0)
在Javascript中,所有变量都绑定到app
,window
又绑定到HeroDetailComponent
。
您应该以{{1}}定义AppComponent
的方式定义(function (app) {
app.HeroDetailComponent = ng.core.Component({
selector: 'hero-detail',
inputs: ['hero'], // <-- this is necessary to receive the "selectedHero"
template: ` <!-- ... --> `
}).Class({
constructor: function () {
}
});
})(window.app || (window.app = {}));
。
index.html
请务必在<!-- 2. Load our 'modules' -->
<script src='app/hero.js'></script>
<script src='app/hero-detail.component.js'></script>
<script src='app/app.component.js'></script>
<script src='app/main.js'></script>
AppComponent
在HeroDetailComponent
中,添加新创建的app.AppComponent = ng.core.Component({
directives: [app.HeroDetailComponent], <-- // note the dependence on the `app` object
// ... and other things
}).Class({ /* Class Declaration */ });
,如此
AFTER