7

我根据 angular.io 入门项目使用种子结构。到目前为止一切正常。

现在我想更改顶部组件以从单独的文件中查看视图,但我遇到了麻烦。工作代码是:

import {Component, View} from 'angular2/core';
@Component({
       selector: 'my-app',
       template: '<h1>Angular2</h1>',
       directives: []
})
export class AppComponent {
       constructor() {  
       }
}

然后我将模板更改为 templateUrl,如下所示:

templateUrl: 'app.component.html',

我在这个文件中的代码与以前完全相同

<h1>Angular2</h1>

似乎很明显可以工作,但事实并非如此。它不会吐出错误,但除了在入门演示中的“正在加载....”消息之外不显示任何内容

感谢您的帮助

彼得

4

7 回答 7

23

在 @Component 装饰器中添加 moduleId: module.id。如果您没有,那么 Angular 2 将在根级别查找您的文件。

import {Component} from 'angular2/core';

@Component({
  selector: 'my-app',
  moduleId: module.id,
  templateUrl: 'app.component.html'
})

export class AppComponent { }  

检查这篇文章

于 2016-05-10T10:04:00.607 回答
4

给出根目录的路径。

于 2016-01-18T11:28:42.490 回答
4

您必须从构建路径写入路径。

templateUrl: 'build/app.component.html'
于 2016-01-18T09:41:27.023 回答
2

如果您使用“主要”组件,则可以使用(绝对路径):

'./your_component_name.html'  

在你的情况下:

'./app.component.html',

如果其他组件 - 你有几个选择:

  1. 如前所述 - 使用 moduleId
  2. 使用/app/your_component_html_filename类似的例子/app/dashboard.html./app/dashboard.html
  3. 使用完整路径 - 不是一个好主意,但你可以

关于使用 .css NOT 从您的“主要”组件:

  1. 使用没有第一个斜杠'/'的app/your_component_css_filename示例!!!app/dashboard.css
于 2017-05-13T19:39:31.613 回答
1

在我的情况下,我通过添加组件的 moduleid 属性解决了这个问题

@Component({
    moduleId: module.id,
    selector: 'my-app',
    // templateUrl: './app/app.component.html'
    templateUrl:'app.component.html'
})

它按预期工作。我从这个网址得到了一些想法:
https ://www.youtube.com/watch?v=WAPQF_GA7Qg&feature=youtu.be

于 2017-11-23T18:09:37.907 回答
1

这里的问题似乎是绝对路径。该组件要求提及绝对路径。这是我的文件结构,

在此处输入图像描述

以下不起作用,

@Component({
    selector: 'pm-products',
    templateUrl: 'product-list.component.html',
    styleUrls: ['product-list.component.css']
})

据我所知,HTML 模板 URL 或样式表的 URL 需要以绝对路径给出。我尝试了以下和工作。

@Component({
    selector: 'pm-products',
    //template: `<h3>PRODUCT LISTINGS </h3>`
    templateUrl:'app/products/product-list.component.html'
})
于 2017-10-08T21:53:57.553 回答
1

使用完整路径,如 app/app.component.html 或使用绝对路径,如 ./app.component.html ./ 用于同一目录

于 2016-06-30T07:10:07.230 回答