templateUrl对我不起作用

时间:2016-01-17 21:54:49

标签: angular angular2-template

我根据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>

似乎很明显可行,但事实并非如此。它不会吐出错误,但除了“loading ....”消息之外,它不显示任何内容,如启动演示

感谢您的帮助

彼得

7 个答案:

答案 0 :(得分: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 { }  

选中此article

答案 1 :(得分:4)

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

templateUrl: 'build/app.component.html'

答案 2 :(得分:4)

从根目录中提供路径。

答案 3 :(得分:1)

使用app / app.component.html等完整路径 或使用像./app.component.html这样的绝对路径 ./对于同一目录

答案 4 :(得分:1)

如果您使用的是主要的&#39;组件,您可以使用(绝对路径):

'./your_component_name.html'  

在你的情况下:

'./app.component.html',

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

  1. 如前所述 - 使用moduleId
  2. 使用/app/your_component_html_filename,例如/app/dashboard.html./app/dashboard.html
  3. 使用完整路径 - 不是一个好主意,但你可以
  4. 关于使用.css NOT来自您的&#39; main&#39;成分:

    1. 使用app/your_component_css_filename,例如示例app/dashboard.css,但不要先使用斜杠&#39; /&#39; !!!

答案 5 :(得分:1)

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

enter image description here

以下不起作用,

@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'
})

答案 6 :(得分: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