Angular 2外部样式不会内嵌到标题中

时间:2016-02-03 22:14:03

标签: css angular angular2-template

我在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 样式部分和外部样式表中的样式都应按角度内联到标题中。

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

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

我正在使用:" angular2":" 2.0.0-beta.2" (最新的beta AFAIK)

3 个答案:

答案 0 :(得分:10)

我做了一些测试,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的绝对路径。见这一行:

希望它可以帮到你, 亨利

答案 1 :(得分:1)

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

答案 2 :(得分:0)

您可以使用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 {

}