簡體   English   中英

Angular 6不應用scss樣式

[英]Angular 6 not applying scss styles

我有一個組件頁面和相應的樣式表,但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。 可能是什么原因? 有人建議嗎?

您的SCSS不適用於您的HTML文件product-detailpage.component.html

原因是Angular使用shadow DOM作為組件。 這意味着在您的組件中找不到標簽<body><app-product-detailpage>

因為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;
}

但最后我建議您使用全局 scss文件來定義<web component>樣式。

根據文檔 ,組件中指定的樣式只能應用於其模板,該模板排除組件。

這就是為什么你的樣式不是從組件的style.scss處理組件的原因,但是從全局樣式表中工作正常。

一種方法是使用: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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM