【问题标题】:templateUrl does not work for metemplateUrl 对我不起作用
【发布时间】:2016-01-17 21:54:49
【问题描述】:

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

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

&lt;h1&gt;Angular2&lt;/h1&gt;

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

感谢您的帮助

彼得

【问题讨论】:

  • 您确定您的模板在正确的目录中吗?如果它与组件在同一目录中,则应为templateUrl: 'app/app.component.html',
  • 尝试将 templateUrl 放入 @View 装饰器中。
  • 谢谢,'app/app.component.html' 更正解决了这个问题。原因尚不清楚。 templateUrl 是否引用了项目根目录?

标签: angular angular2-template


【解决方案1】:

在 @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

【讨论】:

    【解决方案2】:

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

    './your_component_name.html'  
    

    在你的情况下:

    './app.component.html',
    

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

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

    关于在“主”组件中使用 .css 不是:

    1. 使用app/your_component_css_filename,例如app/dashboard.css,不带第一个斜杠'/'!!!

    【讨论】:

    • 顺便说一句,在我使用 CLI 创建的项目中,所有模板/样式路径仅适用于“./your_component_name.html”之类的路径
    【解决方案3】:

    在我的情况下,我通过添加组件的 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

    【讨论】:

      【解决方案4】:

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

      以下不工作,

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

      【讨论】:

        【解决方案5】:

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

        templateUrl: 'build/app.component.html'
        

        【讨论】:

          【解决方案6】:

          给出根目录的路径。

          【讨论】:

            【解决方案7】:

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-10-26
              • 2017-06-30
              • 2014-07-03
              相关资源
              最近更新 更多