我在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)
答案 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
的绝对路径。见这一行:
export function isStyleUrlResolvable(url: string): boolean {
if (isBlank(url) || url.length === 0 || url[0] == '/') return false; // <-----
var schemeMatch = RegExpWrapper.firstMatch(_urlWithSchemaRe, url);
return isBlank(schemeMatch) || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset';
}
希望它可以帮到你, 亨利
答案 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 {
}