我正在构建一个angular2应用程序。当我试图为同一个组件加载多个样式表时,我将面临多个问题。下面是我正在做的事情的代码:
import { Component } from '@angular/core';
@Component({
selector: 'my-tag',
templateUrl: 'my-tag.component.html',
styleUrls: [
'./style1.css',
'./style2.css'
]
})
export class MyTagComponent{}现在我的问题是:
当我尝试从其他目录包含css文件时,如下所示:
styleUrls: [
'./style1.css',
'../public/style2.css'
]我知道错误了
Uncaught Error: Expected 'styles' to be an array of strings.
在浏览器控制台中。
然后,我在组件的目录中包含了第二个样式表style2.css,并编写了第一个片段。现在,样式正在加载,但它正在全球范围内加载。第二个样式表的类名与引导程序冲突,第二个样式表的样式是全局应用的,即其他组件的模板是从第二个样式表中样式的。
styleUrls中列出的urls不应该只应用于组件而不对其他组件造成损害吗?
有人能告诉我如何在不被全局应用的情况下为特定组件加载多个css文件。
我也尝试过以下的解决方法,但这种样式正在应用于我制作的所有组件上。
styles: [
require('./style1.css').toString(),
require('../public/style2.css').toString()
]我正在用webpack作为我的项目的模块绑定器。
webpack.config(excerpt)
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
},
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw'
}发布于 2017-07-27 00:51:36
我见过这样的做法:
@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
}其中app.component.css有多个导入,因此:
@import url('/assets/plugins/bootstrap-datepicker/css/bootstrap-datepicker.css');
@import url('/assets/plugins/bootstrap-datepicker/css/bootstrap-datepicker3.css');
@import url('/assets/plugins/ionRangeSlider/css/ion.rangeSlider.css');
@import url('/assets/plugins/ionRangeSlider/css/ion.rangeSlider.skinNice.css');我希望这能帮到你。
发布于 2016-11-23 11:42:49
我们分别通过设置templateUrl和styleUrls元数据属性来包含模板和CSS文件。由于这些文件与组件位于同一位置,所以最好按名称引用它们,而不必指定返回应用程序根的路径。
我们可以改变角度计算完整URL的方式,将组件元数据的moduleId属性设置为module.id。
@Component({
selector: 'my-tag',
moduleId: module.id,
templateUrl: 'my-tag.component.html',
styleUrls: ['style1.css', 'style2.css']
})
export class MyTagComponent { }Update#1
webpack说:
尝试使用webpack配置中css的“to -string-加载器”。
{ test: /\.css$/, loaders: ['to-string-loader', 'css-loader'] }希望会对你有用。
发布于 2016-11-23 20:57:49
我认为问题在于您传递给ExtractPlugin.extract的'style‘参数(加载程序:options\object)。我认为它引用了这个加载器:https://github.com/webpack/style-loader,它向DOM添加了一个样式标记,因此将在全球范围内应用您的样式。
前几天我遇到了这个问题,只是为了这篇文章才查到了上面的理由,应该回去正确地解决这个问题,但是我只是像这样使用css-加载器来解决这个问题:
{
test: /\.css$/,
loader: "css-loader"
}以及将封装设置为ViewEncapsulation.Native,并如前面所述,在加载的CSS上调用.toString()。不过,我想ExtractTextPlugin仍然可以在删除“样式”加载程序的情况下使用。
https://stackoverflow.com/questions/40763056
复制相似问题