【问题标题】:Angular 2 external style doesn't get inlined to headerAngular 2 外部样式不会内联到标题
【发布时间】:2016-05-13 08:15:03
【问题描述】:

我在 typescript 中有这个组件定义:

import {Component, ViewEncapsulation} from 'angular2/core';

@Component({
    selector: 'my-app',
    templateUrl: '/views/sandbox.html',
    styleUrls: ['/styles/sandbox.css'],
    styles: [`.wow { background-color: red; }`],
    encapsulation: ViewEncapsulation.Emulated
})
export class SandBox { }

根据这篇文章:http://blog.thoughtram.io/angular/2015/06/25/styling-angular-2-components.html 样式部分和外部样式表中的样式都应按角度内联到标题中。

不幸的是,第二个没有被注入,角度只注入了样式部分中的一个。

我试过从浏览器访问/styles/sandbox.css,没问题。 Angular 也能够访问 /views/sandbox.html,所以我不知道为什么它没有发生。

我正在使用:“angular2”:“2.0.0-beta.2”(最新测试版 AFAIK)

【问题讨论】:

  • 删除 styleUrls 属性时是否注入?
  • 总是注入“样式”。另一个不是。
  • 你不能把你的绝对 URL 中的第一个斜杠去掉,让它看起来像这样 styles/sandbox.css 吗?这对我有用。

标签: css angular angular2-template


【解决方案1】:

我做了一些测试,奇怪的是sandbox.css 的样式仅适用于styleUrls 属性中的相对路径:

@Component({
  selector: 'my-app',
  templateUrl: '/views/sandbox.html',
  styleUrls: ['../styles/sandbox.css'],
  styles: [`.wow { background-color: red; }`],
  encapsulation: ViewEncapsulation.Emulated
})
export class AppComponent {
  constructor() {
  }
}

编辑

查看源代码后,Angular2 会阻止 styleUrls 使用绝对路径。看到这一行:

希望对你有帮助 蒂埃里

【讨论】:

  • 它有效,谢谢!但是,我想知道这是否是一个错误......因为绝对网址适用于“templateUrl”,但不适用于“styleUrls”
  • 在查看了源代码后,有一个测试阻止了使用它...我更新了我的答案。
  • 我在 Angular 存储库中添加了一个关于此的问题:github.com/angular/angular/issues/6905。我期待着得到他们的答复;-)
【解决方案2】:

解决此问题的最佳方法是为您的组件使用另一个 css 文件并将其添加到您的 StyleUrls 列表中。更简洁,并且会随着组件的增长而扩展。

【讨论】:

    【解决方案3】:

    可以使用systemjs和commonjs模块依赖加载器,加载模板、样式等文件。

    在 commonjs moduleId 中:module.id 在systemJs __moduleName

    import {Component} from '@angular/core';
    
    @Component({
    
    moduleId:module.id,
    selector: "exf-header",
    templateUrl: "header.html",
    styleUrls:['header.css']
    
    })
    
    export class HeaderComponent {
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 2013-07-19
      相关资源
      最近更新 更多