javascript - How to programmatically add a css rule to an element
问题描述
I am using Angular 6 and Typescript. Here's my issue. I need to add a specific CSS rule to the host of a component that I am writing. I cannot apply that rule systematically, I need to have some logic in ngOnInit()
before adding my rule. I know this sounds like bad practice, but there are no workarounds and this is the only way I can solve the problem I am facing. I can easily add classes on new styles to my host, but I cannot seem to find a way to add a rule.
Some people have been marking my question as a duplicate. Please read my question carefully. I am not trying to add a class, I am trying to a add a RULE. This is very different and there are no results for such question.
Here's the two rules I have that I want to add to my host element depending on some condition:
custom-component + custom-component > .vertical-component {
margin-top: 1rem;
}
and
custom-component + custom-component > .horizontal-component {
margin-left: 1rem;
}
In my component code, I have something like this:
export class CustomComponent {
public constructor(private host: ElementRef, private renderer: Renderer2) {
}
public applyStylesToHost(): void {
if (this.variant == TYPE.VERTICAL) {
// Set the rule with the margin-top
} else {
// Set the rule with the margin-left
}
}
}
I was looking for a method like this.renderer.setRule()
, but there is no such thing. How can I programmatically add a specific rule to my host element?
The closest thing I found is this link. The author suggest doing document.createElement("style").sheet.addRule()
, but when I tried to do it, the method addRule
didn't exist on the sheet
element.
解决方案
如果你想走这条路,你应该使用大概的方法:
renderer.setStyle(...)
或者
renderer.addClass(...)
renderer.removeClass(...)
我建议阅读Renderer2的文档
推荐阅读
- python - 如何解决错误:在mac上标记“(”之前缺少二元运算符?
- java - 如何访问运行时新添加的资源?JAVA 弹簧靴
- c++ - 更改 C++ 控制台应用程序的背景颜色
- java - 异常处理程序后,Rest 模板不返回响应实体
- reporting-services - SSRS 动态参数值未刷新
- mysql - 如何减少子查询中的 JOIN?
- android - 使用 Firebase 将数据回收器适配器传递给其他活动
- jakarta-ee - Spring-Batch @StepScope 和 @JobScope 不适用于带有转换的 Job 中使用的 Step
- c# - .NET CORE 中的“指定密码模式对此算法无效”,但在 .NET Standard 中工作
- rpm - 只下载最新版本的软件