我正在关注 angular tutorial关于 Angular2 的基础知识,尝试将其转换为 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
最佳答案
在 Javascript 中,所有变量都绑定(bind)到 app
,而 app
又绑定(bind)到 window
。
您应该以定义 AppComponent
的方式定义 HeroDetailComponent
。
(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 */ });
关于javascript - Angular2使用javascript从外部文件加载组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37988437/