我正在开发 Angular 应用程序,我面临一个问题,即组件中定义的样式未按预期应用。我尝试了多种故障排除步骤,但似乎都不起作用。相同的设置适用于新创建的 Angular 项目,因此我怀疑我现有的项目配置可能存在问题。
1.** 组件设置:** 我有一个简单的 Angular 组件,其内联样式应将 h1 元素的颜色更改为红色。
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'cm-test',
templateUrl: './test.component.html',
styles: [
`h1 { color: red !important; }`
],
encapsulation: ViewEncapsulation.None // I changed this to None
})
export class TestComponent implements OnInit {
constructor() { }
ngOnInit(): void { }
}
2.HTML 模板: 组件的 HTML 模板包含 h1 元素:
<h1>test works!</h1>
3.问题: 颜色:红色!重要样式未应用于 h1 元素。尽管尝试了以下解决方案,但样式并不适用:
Try it with these 2 solutions and check.
Solution-1
@Component({
selector: 'cm-test',
templateUrl: './test.component.html',
styles: [
':host h1 { color: red !important; }'
],
encapsulation: ViewEncapsulation.None
})
export class TestComponent {}
Solution-2
styles: [
'::ng-deep h1 { color: red !important; }'
]