带有JavaScript的外部文件的Angular2加载组件



我正在关注Angular2基础知识的Angular教程,试图将其转换为JavaScript,因为它目前仅适用于打字稿。

我目前有两个文件:app.component.js and 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中,所有变量均绑定到 app,后者依次绑定到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,例如So

app.AppComponent = ng.core.Component({
  directives: [app.HeroDetailComponent], <-- // note the dependence on the `app` object
  // ... and other things
}).Class({ /* Class Declaration */ });

最新更新