【问题标题】:Angular 2 EXCEPTION: The selector "app" did not match any elementsAngular 2 例外:选择器“app”不匹配任何元素
【发布时间】:2021-07-19 05:39:15
【问题描述】:

当我尝试运行我非常基本的 Angular 2 代码时,Chrome DevTools 给了我以下异常:

例外:选择器“app”没有匹配任何元素

三个相关文件是:

(1) boot.ts

///<reference path="../node_modules/angular2/typings/browser.d.ts"/>
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from "./app.component";

bootstrap(AppComponent);

(2) app.component.ts

import {Component} from 'angular2/core';
import {PuzzleComponent} from "./puzzle/puzzle.component";

@Component({
    selector: 'app',
    template: `
        <my-puzzle></my-puzzle>
        `,
    directives: [PuzzleComponent]
})
export class AppComponent {

}

(3) puzzle.component.ts

import {Component} from 'angular2/core';

@Component({
    selector: 'my-puzzle',
    template: `
        Random text
        `
})
export class PuzzleComponent{

}

我已经确认我的开发工作区没有问题;其他代码按预期工作。这是 Udemy 课程Angular 2 的完整指南,我已经输入了几次代码,试图找出任何拼写错误。任何帮助将不胜感激 - 谢谢!

【问题讨论】:

  • 您的问题中是否存在未包含的主要 HTML 文件?
  • 看起来不错。你的index.html 呢?在这里向我们展示。
  • TS 文件看起来不错。需要看看你如何引用 boot.ts 并在主 html 文件中使用“app”标签。

标签: angular


【解决方案1】:

你的body元素需要包含&lt;app&gt;&lt;/app&gt;

<body>
  <app></app>
</body>

【讨论】:

  • 哇,我的 index.html 文件中的开始标记为 my-app,结束标记为 app - 谢谢!
  • 没有 元素我的自定义组件名称不起作用!哇!!
【解决方案2】:

确定您使用应用路由模块并且必须更改 选择器:“应用程序”到“应用程序根” app.component.ts:

   @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })

【讨论】:

    猜你喜欢
    • 2016-06-09
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 2016-11-24
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多