title: How to programmatically add a css rule to an element
body: <p>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 <code>ngOnInit()</code> 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. </p>
  
  <p>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.</p>
  
  <p>Here's the two rules I have that I want to add to my host element depending on some condition:</p>
  
  <pre><code>custom-component + custom-component &gt; .vertical-component {
      margin-top: 1rem;
  }
  </code></pre>
  
  <p>and </p>
  
  <pre><code>custom-component + custom-component &gt; .horizontal-component {
      margin-left: 1rem;
  }
  </code></pre>
  
  <p>In my component code, I have something like this:</p>
  
  <pre><code>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
          }
      }
  }
  </code></pre>
  
  <p>I was looking for a method like <code>this.renderer.setRule()</code>, but there is no such thing. How can I programmatically add a specific rule to my host element?</p>
  
  <p>The closest thing I found is <a href="https://davidwalsh.name/add-rules-stylesheets" rel="nofollow noreferrer">this link</a>. The author suggest doing <code>document.createElement("style").sheet.addRule()</code>, but when I tried to do it, the method <code>addRule</code> didn't exist on the <code>sheet</code> element.</p>