我有一个组件页面和相应的样式表,但是component.scss中的类并不适用于该页面。没有错误,我仍然想知道为什么?
这是我的产品-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。可能的原因是什么?有人能建议一下吗?
发布于 2018-06-26 07:37:34
您的SCSS将不适用于您的HTML文件产品-Detailpage.Component.html。
原因是Angular使用shadow DOM作为组件。这意味着在您的组件中找不到标记<body>和<app-product-detailpage>。
发布于 2018-06-26 07:32:50
根据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.
发布于 2018-06-26 11:54:20
因为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 component>的样式。
https://stackoverflow.com/questions/51032932
复制相似问题