templateUrl对我不起作用

问题描述 投票:7回答: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>

工作似乎很明显,但事实并非如此。它没有吐出错误,但它不显示除了“loading ....”消息之外的任何内容,如在入门演示中那样

谢谢你的帮助

彼得

angular angular2-template
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 { }  

检查这个article


4
投票

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

templateUrl: 'build/app.component.html'

4
投票

从根目录中提供路径。


1
投票

使用像app / app.component.html这样的完整路径,或者使用./app.component.html ./这样的绝对路径作为同一目录


1
投票

如果您使用'main'组件,则可以使用(绝对路径):

'./your_component_name.html'  

在你的情况下:

'./app.component.html',

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

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

关于从'main'组件使用.css NOT:

  1. 使用app/your_component_css_filename像示例app/dashboard.css没有第一个斜线'/'!

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

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

© www.soinside.com 2019 - 2024. All rights reserved.