Angular2 组件未呈现

Angular2 component not rendered

我有 AngularJS 的经验,正在开始学习 Angular2。我正处于学习之旅的最开始,但我已经卡住了。

我可以渲染我的一个组件,但不能渲染另一个。我正在使用 Visual Studio 2013 Ultimate 和 TypeScript 1.5 beta。这是来源:

index.html

<html>
    <head>
        <title>Angular 2 Quickstart</title>
        <script src="https://github.jspm.io/jmcriffey/bower-traceur-runtime@0.0.87/traceur-runtime.js"></script>
        <script src="https://jspm.io/system.js"></script>
        <script src="https://code.angularjs.org/2.0.0-alpha.28/angular2.dev.js"></script>
    </head>
    <body>

        <!-- The app component created in app.ts -->
        <my-app></my-app>
        <display></display>
        <script>
            System.import('app');
            System.import('displ');
        </script>
    </body>
</html>

app.ts

/// <reference path="d:/npm/typings/angular2/angular2.d.ts" />

import { Component, View, bootstrap} from 'angular2/angular2';

// Annotation section
@Component({
    selector: 'my-app',
})

@View({
    template: '<h1>Hello {{ name }}</h1>',
})

// Component controller
export class MyAppComponent {
    name: string;

    constructor() {
        this.name = 'Alice';
    }
}

bootstrap(MyAppComponent);

displ.ts

/// <reference path="d:/npm/typings/angular2/angular2.d.ts" />

import { Component, View, bootstrap} from 'angular2/angular2';

// Annotation section
@Component({
    selector: 'display'
})

@View({
    template: '<h1>xxxHello {{ name }}</h1>',
})

// Component controller
export class DisplayComponent {
    name: string;

    constructor() {
        this.name = 'Bob';
    }
}

结果很简单:

你好爱丽丝

鲍勃去哪儿了?

谢谢!

更新

我意识到我试图以错误的方式去做。我的意图是将 display 组件嵌套在 my-app 组件中,但是 my-app 的模板没有包含必要的成分:

  1. 它不包含 <display></display> 元素。这被包含在顶层 index.html 这是错误的地方。
  2. 视图注释未将显示组件作为指令引用。

简而言之,我应该拥有的是:

app.ts(查看注释)

@View({
    template: '<h1>Hello {{ name }}</h1><display></display>',
    directives: [DisplayComponent]
})

而且我还必须将显示组件导入 app.ts:

import { DisplayComponent } from 'displ';

请添加 bootstrap(DisplayComponent);,因为 已经指出。

来自quickstart

The bootstrap() function takes a component as a parameter, enabling the component (as well as any child components it contains) to render.

所以是的,您确实需要为所有组件调用 bootstrap,除非它们是另一个组件的子组件。