【问题标题】:Angular2 component not renderedAngular2组件未呈现
【发布时间】:2015-07-16 08:36:48
【问题描述】:

我有 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. 它不包含&lt;display&gt;&lt;/display&gt; 元素。而是将其包含在顶级 index.html 中,这是错误的位置。
  2. 视图注释没有包含显示组件作为指令引用。

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

app.ts(查看注释)

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

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

import { DisplayComponent } from 'displ';

【问题讨论】:

  • bootstrap(DisplayComponent); ?
  • @nada 是否有必要引导每个组件?
  • 通常我们只需要引导根组件,我们将其他组件作为指令包含在其中。这是我们只需要引导根。如果您分别引导这两个组件,它们将是两个独立的 Angular 2 应用程序

标签: typescript angular


【解决方案1】:

请添加bootstrap(DisplayComponent); nada 已经指出。

来自quickstart

bootstrap() 函数将组件作为参数,启用 要渲染的组件(以及它包含的任何子组件)

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

【讨论】:

  • 好的,因为我对这个很陌生,我刚刚意识到我必须将我的第二个组件作为指令包含在第一个......
  • 除了使用指令之外,一个组件是否可以包含其他组件?
  • @AviadP.: 如果你想让一个组件成为另一个组件的子组件。我认为您使用指令的方式是我知道的唯一方式。
  • 这在最新版本的 Angular 中不起作用 - 不推荐向组件添加 @directive。
猜你喜欢
  • 1970-01-01
  • 2017-02-07
  • 2014-08-12
  • 2016-10-29
  • 2013-06-08
  • 2018-05-30
  • 2021-11-19
  • 1970-01-01
相关资源
最近更新 更多