[Angular] Modify :before / :after value from Javascirpt

Let's say we want to dynamiclly change some style in :before or :after element.

We cannot use NgStyle, it doesn's support this use case, what we can do:

Using css variable + setProperty

import { Component, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <p #ref>
      Start editing to see some magic happen :)
    </p>
  `,
  styles: [ `
      :host {
        --color: blue;
      }
      p {
        font-family: Lato;
        color: green
      }
      p:before {
        content: 'content from :before';
        color: var(--color);
      }
  ` ]
})
export class AppComponent {
  @ViewChild('ref') p: ElementRef

  ngOnInit() {
    this.p.nativeElement.style.setProperty('--color', 'red')
  }
}

 

Guess you like

Origin www.cnblogs.com/Answer1215/p/12602678.html