Angular 6未应用scss样式。

13

我有一个组件页面和相应的样式表,但是组件.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 进行更改,它可以正常工作。为了检查,我将 body 的颜色更改为绿色,它也可以工作。

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


我遇到了类似的问题,并通过使用“封装.none”来解决。我是通过使用rootViewRef来以编程方式渲染组件的,因此它没有自己的影子DOM。 - Lennon
1
这是正确的答案 https://dev59.com/5VYO5IYBdhLWcg3wL-rY#46218064 - Sean Chase
请阅读此文章,其中有许多解决方案(https://angular.io/guide/component-styles)。 - Serkan KONAKCI
3个回答

10

你的 SCSS 无法应用到 HTML 文件 product-detailpage.component.html 中。

原因是 Angular 在组件中使用了shadow DOM。这意味着标签<body><app-product-detailpage>在你的组件中不存在。


2
不对,这是错误的。默认情况下,Angular会模拟样式封装,当你将视图封装设置为本地ViewEncapsulation.Native时,它会使用影子DOM。 - Vikas
https://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html - Vikas

8

由于Angular中的默认css封装方式为Emulated(ViewEncapsulation.Emulated),因此Angular将呈现如下:

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

如果您想为当前的组件设置样式,可以使用Native选项。

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

它将呈现为:
input {
    border-radius: 5px;
}

但是最终我建议您使用全局的scss文件来定义<web组件>的样式。


3
ViewEncapsulation.Native 已被弃用,请改用 ViewEncapsulation.ShadowDom。详见:https://angular.io/api/core/Component#encapsulation - Denis Evseev

8
根据文档,组件中指定的样式只能应用于其模板,而不包括组件本身。
这就是为什么您从组件的style.scss中设置样式时不起作用,但从全局样式表中设置样式却可以生效的原因。
一种解决方法是根据此文档使用:host伪选择器,它允许在放置组件的容器上添加样式。
文档中说:
:host选择器是目标主机元素的唯一方法。您无法使用其他选择器从组件内部访问主机元素,因为它不是组件自己模板的一部分。主机元素在父组件的模板中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接