【问题标题】:Angular 6 not applying scss stylesAngular 6 不应用 scss 样式
【发布时间】:2018-12-04 14:06:01
【问题描述】:

我有一个组件页面和相应的样式表,但是 component.scss 中的类不适用于该页面。没有错误,我仍然想知道为什么?

这是我的 product-detailpage.component.html

<div>
  <h1>Product Detail Page</h1>
</div>

这是 .ts 文件

import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {ProductdetailService} from '../productdetail.service';
@Component({
  selector: 'app-product-detailpage',
  templateUrl: './product-detailpage.component.html',
  styleUrls: ['./product-detailpage.component.scss']
})
export class ProductDetailpageComponent implements OnInit {

  constructor(private route: ActivatedRoute, private productData: ProductdetailService) {
    this.route.params.subscribe(params => console.log(params));
   }

  ngOnInit() {
  }

}

这是 .scss 文件

body{color:Red !important}
app-product-detailpage{
        h1{color:red !important}
}

但是我注意到的一件事是,如果我对全局 styles.css 进行更改,它可以正常工作。只是为了检查我将身体颜色更改为绿色并且它可以工作。

我的 Angular 应用程序配置为使用 scss。可能是什么原因?有人可以建议吗?

【问题讨论】:

标签: css angular sass


【解决方案1】:

您的 SCSS 不适用于您的 HTML 文件product-detailpage.component.html

原因是 Angular 使用 shadow DOM 作为组件。这意味着标签 &lt;body&gt;&lt;app-product-detailpage&gt; 在您的组件中找不到。

【讨论】:

【解决方案2】:

根据documentation,组件中指定的样式只能应用于其模板,不包括组件。

这就是为什么您的样式在组件的 style.scss 中无法在组件上运行但在全局样式表中运行良好的原因。

一种方法是使用:host 伪选择器,就像this documentation 一样,它允许在放置组件的容器上添加样式。

文档说 -

The :host selector is the only way to target the host element. You can't reach the host element from inside the component with other selectors because it's not part of the component's own template. The host element is in a parent component's template.

【讨论】:

    【解决方案3】:

    因为Angular 中的默认 css 封装是 Emulated(ViewEncapsulation.Emulated),所以 Angular 将呈现如下:

    input[_ngcontent-c0] {
        border-radius: 5px;
    }
    

    所以如果你想将样式设置为当前的component,你可以使用Native选项。

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      encapsulation : ViewEncapsulation.Native
    })
    

    它将呈现为:

    input {
        border-radius: 5px;
    }
    

    但最后我建议你使用 global scss 文件来定义&lt;web component&gt; 的样式。

    【讨论】:

    猜你喜欢
    • 2020-02-13
    • 2019-03-25
    • 2021-03-21
    • 2018-11-10
    • 2018-02-28
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多