【问题标题】:Angular 2 component style is being applied globallyAngular 2 组件样式正在全球范围内应用
【发布时间】:2018-03-25 15:14:00
【问题描述】:

我正在尝试仅为该组件使用组件特定样式,但它正在用于所有其他组件。我有 webpack 设置。我尝试了不同的方法,但它没有按预期工作。谁能帮我解决这个问题。 Webpack 配置:

    /*
     * to string and css loader support for *.css files
     * Returns file content as string
     *
     */
    {
      test: /\.css$/,
      use: ['to-string-loader', 'css-loader']
    },
    /*
     * to string and css loader support for *.css files
     * Returns file content as string
     *
     */
    {
      test: /\.(scss|sass)$/,
      use: ['to-string-loader', 'style-loader', 'css-loader', 'sass-loader'],
    },

我的组件声明:

@Component({
  selector: 'outbreak-visualization',
  templateUrl: './outbreak-visualization.component.html',
  styleUrls: ['./outbreak-visualization.component.scss']
})

我的应用组件声明

@Component({
  selector: 'app',
  encapsulation: ViewEncapsulation.None,
  styleUrls: [
    './app.component.global.scss'
  ],
  template: `.....

【问题讨论】:

  • 确保组件特定样式不会被全局样式覆盖
  • 嗯,您正在使用encapsulation: ViewEncapsulation.None 配置您的应用程序。这意味着您的所有样式都没有被封装。删除此行并在styles: [...] 部分的.angular-cli.json 中添加您的全局样式。
  • 它没有被覆盖,但我可以看到每个页面中的所有样式: @Danielomi : 不使用 .angular-cli.json 而是 webpack。

标签: angular sass styles webpack-2


【解决方案1】:

试试这样:

我在以下位置有全局 scss 文件:

src => app => app.component.global.scss

app.component.global.scss

body {
    background: #000 !important;
}

我在以下位置有 style.scss 文件:

style.scss

@import "src/app/app.component.global.scss";

在 angular-cli.json 的样式数组中添加你的 style.scss

"styles": [
  "styles.scss"
]

【讨论】:

    猜你喜欢
    • 2016-10-02
    • 1970-01-01
    • 2016-04-28
    • 2017-03-01
    • 2012-12-31
    • 2022-09-30
    • 2018-03-29
    • 1970-01-01
    • 2016-09-30
    相关资源
    最近更新 更多