How to detect if <html> tag has a class in child Angular component

题意

如何检测 <html> 标签在子 Angular 组件中是否有类?

问题背景:

I have a dynamic class which is applied on html tag when user presses the button to switch view to dark mode:

我有一个动态类,当用户按下按钮切换到暗黑模式时,应用于 <html> 标签。

html 复制代码
<html lang="en" class="app-dark-theme">

Now in child Angular component I need to check if this class exists on html tag to style one particular class in this child component.

现在,在子 Angular 组件中,我需要检查 <html> 标签上是否存在这个类,以便为该子组件中的某个特定类应用样式。

How can I achieve this? I tried :has() pseudo-selector but it didn't work for me.

我怎么才能实现这个呢?我试过 :has() 伪选择器,但它对我不起作用。

css 复制代码
  html:has(.app-dark-theme) {
    .test-class {
      border: 1px solid var(--p-blue-200);
    }
  }

Preferable solution is pure CSS/SCSS if possible.

如果可能的话,优先使用纯 CSS/SCSS 解决方案。

Thanks.

问题解决:

The issue is most likely caused by 问题很可能是由以下原因引起的: Angular Style scoping.

By default, Angular uses emulated encapsulation so that a component's styles only apply to elements defined in that component's template. In this mode, the framework generates a unique HTML attribute for each component instance, adds that attribute to elements in the component's template, and inserts that attribute into the CSS selectors defined in your component's styles. See more in Angular docs

Consequently, the following component style

因此,以下组件样式

css 复制代码
  html.app-dark-theme {
    .test-class {
      border: 1px solid var(--p-blue-200);
    }
  }

results in something similar to

导致类似于以下的结果:

javascript 复制代码
// _ngcontent-ng-c2903067727 is the unique HTML attribute added by Angular
// It is not specified on the html element so the CSS rule doesn't match anything
html.app-dark-theme[_ngcontent-ng-c2903067727] .test-class[_ngcontent-ng-c2903067727] {
  border: 1px solid var(--p-blue-200);
}

To get around that, the Angular docs suggest to use :host-context() in your component styles

为了解决这个问题,Angular 文档建议在组件样式中使用 :host-context()

css 复制代码
:host-context(html.app-dark-theme) {
  .test-class {
    border: 1px solid var(--p-blue-200);
  }
}
相关推荐
熊猫钓鱼>_>15 分钟前
动态网站发布部署核心问题详解
前端·nginx·容器化·网页开发·云服务器·静态部署
方也_arkling15 分钟前
elementPlus按需导入配置
前端·javascript·vue.js
顾西爵霞23 分钟前
个人学习主页搭建指南:从毛坯房到精装户型
学习·html
爱吃大芒果26 分钟前
Flutter for OpenHarmony 实战: mango_shop 资源文件管理与鸿蒙适配
javascript·flutter·harmonyos
我的xiaodoujiao29 分钟前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 44--将自动化测试结果自动推送至钉钉工作群聊
前端·python·测试工具·ui·pytest
沛沛老爹31 分钟前
Web开发者转型AI:多模态Agent视频分析技能开发实战
前端·人工智能·音视频
David凉宸37 分钟前
vue2与vue3的差异在哪里?
前端·javascript·vue.js
Irene199137 分钟前
JavaScript字符串转数字方法总结
javascript·隐式转换
笔画人生42 分钟前
Cursor + 蓝耘API:用自然语言完成全栈项目开发
前端·后端
AC赳赳老秦1 小时前
外文文献精读:DeepSeek翻译并解析顶会论文核心技术要点
前端·flutter·zookeeper·自动化·rabbitmq·prometheus·deepseek