简体   繁体   English

组件中的样式无效,但可在index.html中使用。 (角度2+)

[英]Styles in component not working, but works in index.html. (Angular 2+)

Hello I am working with an Angular 2+ project, and I am adding a third party library called DHTMLX Gantt Chart. 您好,我正在使用Angular 2+项目,并且正在添加一个名为DHTMLX Gantt Chart的第三方库 I have everything set up and working, but I have an odd problem with the styles. 我已经完成所有工作,但是样式却有一个奇怪的问题。

I have a component folder with the three main files: 我有一个包含三个主要文件的组件文件夹:

mycomponent.component.html

mycomponent.component.css

mycomponent.component.ts . mycomponent.component.ts

In mycomponent.component.css I imported in the library styles like so: mycomponent.component.css我导入的库样式如下:

@import "../../../../node_modules/dhtmlx-gantt/codebase/dhtmlxgantt.css";

And for some reason when I compile and load the chart, these styles aren't catching and fail to attach themselves to the html. 出于某种原因,当我编译并加载图表时,这些样式无法捕获,并且无法将其自身附加到html。

But when I import the styles in the index.html like this: 但是,当我像这样在index.html导入样式时:

<style>
  @import "../node_modules/dhtmlx-gantt/codebase/dhtmlxgantt.css";
</style>

And compile, it seems to work just fine. 并进行编译,似乎工作正常。

I've triple checked the paths, and know for sure that they are correct for both instances. 我已经对路径进行了三重检查,并确定它们对于两个实例都是正确的。

I'm wondering if its failing because of the order in which the styles/components/chart are loading? 我想知道它是否由于加载样式/组件/图表的顺序而失败?

Is there a solution where I can keep the style import in my component css? 有什么解决方案可以将样式导入保留在组件CSS中?

Thanks! 谢谢!

@import "../../../../node_modules/dhtmlx-gantt/codebase/dhtmlxgantt.css";

It's only importing your css as string, when in reality what you want is your vendor css in a style tag. 它实际上只是将CSS作为字符串导入,而实际上您想要的是样式标记中的供应商CSS。

In the MyComponent.component.ts there's no encapsulation, because of this line encapsulation: ViewEncapsulation.None , which means any css rules will be applied globally to your app. 由于存在以下行封装,因此在MyComponent.component.ts中没有封装: ViewEncapsulation.None ,这意味着所有css规则都将全局应用于您的应用。 So you can import the bootstrap styles in your app component: 因此,您可以在应用程序组件中导入引导样式:

@Component({
  selector: 'app',
  encapsulation: ViewEncapsulation.None,
  styleUrls: [
    './mycomponent.component.css',
    '../../../../node_modules/dhtmlx-gantt/codebase/dhtmlxgantt.css'
  ],

Edit 编辑

If you check config/webpack.commons.js you will find this rule: 如果您检查config / webpack.commons.js ,则会发现以下规则:

{
    test: /\.css$/,
    loaders: ['to-string-loader', 'css-loader']
},

This rule allows your components to import the css files, basically this: 该规则允许您的组件导入css文件,基本上是这样的:

@Component({
  selector: 'app',
  encapsulation: ViewEncapsulation.None,
  styleUrls: [
    './app.component.css' // this why you import css as string
  ],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM