未应用角度组件样式

问题描述 投票:0回答:1

我正在开发 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 元素。尽管尝试了以下解决方案,但样式并不适用:

  • 使用 ViewEncapsulation.None (禁用组件级范围)
  • 已使用::ng-deep(已弃用,但仍然有效)
  • 尝试过的颜色:红色,无!重要
  • 检查浏览器开发人员工具以确保样式没有被覆盖
  • 使用简单的内联样式进行测试,例如 h1 { color: red; }
  • 清除浏览器缓存并重建 Angular 项目
  • 在单独的文件中添加样式并将其导入到 styleUrls 中
angular angularjs angular-material
1个回答
0
投票
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; }'
  ]
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.