javascript - Angular2使用javascript从外部文件加载组件

标签 javascript angular

我正在关注 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/

相关文章:

javascript - 无法设置 null javascript 错误的属性

javascript - 使用 jQuery UI 从选择选项中获取值

javascript - Ng-Repeat 只能运行一次

javascript - JavaScript 中的嵌套数组属性分组

javascript - Html 隐藏按钮隐藏所有按钮而不是一个

angular - `(keyup.backspace)` 无法捕获 'shift + backspace'

javascript - 如何在 javascript 中创建动态正则表达式来验证十进制数

angular - 无法解析 [...] 的所有参数

javascript - ERROR TypeError : data. 切片不是函数

angular - Karma 不会 headless 运行 ng 测试