我有一个组件页面和相应的样式表,但是component.scss中的类不适用于该页面。没有错误,我仍然想知道为什么吗?
这是我的product-detailpage.component.html
<div>
<h1>Product Detail Page</h1>
</div>
Run Code Online (Sandbox Code Playgroud)
这是.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() {
}
}
Run Code Online (Sandbox Code Playgroud)
这是.scss文件
body{color:Red !important}
app-product-detailpage{
h1{color:red !important}
}
Run Code Online (Sandbox Code Playgroud)
但是我注意到的一件事是,如果我对global styles.css进行了更改,它就可以正常工作。只是检查一下,我将主体颜色更改为绿色,并且可以正常工作。
我的角度应用程序配置为可与scss一起使用。可能是什么原因?有人可以建议吗?
根据文档,组件中指定的样式只能应用于其模板,该模板不包括该组件。
这就是为什么您的样式在组件的 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.
因为默认的css封装Angular为,所以Angular的渲染如下:Emulated(ViewEncapsulation.Emulated
input[_ngcontent-c0] {
border-radius: 5px;
}
Run Code Online (Sandbox Code Playgroud)
因此,如果要将样式设置为current component,则可以使用Nativeoption。
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation : ViewEncapsulation.Native
})
Run Code Online (Sandbox Code Playgroud)
它将呈现为:
input {
border-radius: 5px;
}
Run Code Online (Sandbox Code Playgroud)
但最后我建议您使用全局 scss文件定义的样式<web component>。
| 归档时间: |
|
| 查看次数: |
11601 次 |
| 最近记录: |