Angular2 Selector与嵌套组件中的任何元素都不匹配

时间:2015-10-23 19:40:34

标签: angular

我有两个嵌套的@Components en angular 2.视图渲染得很好,但它第一次总是抛出一个javascript错误。 这是我在Typescript中的代码。

应用HTML:

<body>
    <my-app>loading...</my-app>
</body>

应用组件:

import {bootstrap, Component} from 'angular2/angular2';
import {CanvasComponent} from "./CanvasComponent";

@Component({
  selector: 'my-app',
  template: `
      <h1>{{title}}</h1>
      <h2>My Games</h2>
      <div>
        <my-canvas></my-canvas>
      </div>
  `,
  directives: [CanvasComponent]
})

class AppComponent {
}

bootstrap(AppComponent);

画布组件:

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

@Component({
  selector: 'my-canvas'
})

@View({
  template: `
  <div>
    <span>Balls:</span>
    <div>{{canvas.length}}</div>
  </div>
  `
})

export class CanvasComponent {
  canvas = [1,2,3];
}

bootstrap(CanvasComponent);

错误是:

EXCEPTION: The selector "my-canvas" did not match any elements

3 个答案:

答案 0 :(得分:53)

expr3文件中删除bootstrap(CanvasComponent)。它正在尝试使用CanvasComponent作为根第二次引导应用程序,并在App HTML中查找CanvasComponent元素。当然找不到它。

答案 1 :(得分:17)

我通过更改index.html中的名称来解决问题,您应该确保index.html中的标记与主要组件中的标记相同。

    <html>
      <head>
        <title>Angular 2 QuickStart</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="stylesheets/styles.css">
        <!-- 1. Load libraries -->
         <!-- Polyfill(s) for older browsers -->
        <script src="node_modules/core-js/client/shim.min.js"></script>
        <script src="node_modules/zone.js/dist/zone.js"></script>
        <script src="node_modules/reflect-metadata/Reflect.js"></script>
        <script src="node_modules/systemjs/dist/system.src.js"></script>
        <!-- 2. Configure SystemJS -->
        <script src="systemjs.config.js"></script>
        <script>
        System.import('app').catch(function(err){ console.error(err); });
        </script>
      </head>
      <!-- 3. Display the application -->

      <body>
        <my-app>Loading...</my-app> <!-- THIS TAG SHOULD BE THE SAME THAT THE SELECTOR IN THE MAIN COMPONENT -->
      </body>
    </html>

<!-- end snippet -->

  </body>
</html>

答案 2 :(得分:0)

在我的index.html中,我不见了

<base href="/">

所以需要的最小值是

<!doctype html>
<head>
    <base href="/">
</head>
<body>
    <your-selector></your-selector>
</body>
</html>