首页 文章

Angular 6不应用scss样式

提问于
浏览
2

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

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

3 回答

  • 1

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

    原因是Angular使用shadow DOM作为组件 . 这意味着您的组件中找不到标签 <body><app-product-detailpage> .

  • 2

    因为 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文件来定义 <web component> 的样式 .

  • 2

    根据documentation,组件中指定的样式只能应用于其模板,该模板排除组件 .

    这就是为什么你的样式不是从组件的style.scss处理组件的原因,但是从全局样式表中工作正常 .

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

    文件说 -

    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.

相关问题