Currently working with Angular 6 and Typescript, I am facing a unique challenge. My task involves adding a specific CSS rule to the host of a component that I am currently developing. Unfortunately, applying this rule systematically is not an option. Instead, I need to incorporate logic within the ngOnInit()
function before implementing the rule. While I understand that this approach may raise concerns regarding best practices, it appears to be the only viable solution for resolving the issue at hand. Although I can easily append classes for new styles to my host element, finding a method to add a rule has proven to be more elusive.
Despite some individuals identifying my query as a duplicate, it is important to differentiate the nature of my request. Rather than seeking to add a class, my goal revolves around introducing a RULE; a distinction that has not yielded any relevant results through previous searches.
The specific rules that I aim to apply to my host element are contingent upon certain conditions:
custom-component + custom-component > .vertical-component {
margin-top: 1rem;
}
and
custom-component + custom-component > .horizontal-component {
margin-left: 1rem;
}
Within my component's code structure, I have outlined the following snippet:
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
}
}
}
My quest for a suitable method akin to this.renderer.setRule()
proved futile, as no such functionality exists within the framework. Therefore, the core challenge lies in identifying how to dynamically introduce a specific rule to my host element.
A potential lead I stumbled upon was presented in this resource, wherein the author discusses a technique involving
document.createElement("style").sheet.addRule()
. However, upon attempting to implement this suggestion, I encountered an obstacle in locating the addRule
method within the sheet
element.