1

How can e.g. access and set the background-color of the ::after pseudo selector of the element below?

@ViewChild('infobubble', { read: ElementRef }) infoBubbleElement: ElementRef;

  ngAfterViewInit(): void {
    const elem = this.infoBubbleElement.nativeElement;
    elem.style.backgroundColor = 'green';
  }
Carli Beeli
  • 790
  • 1
  • 11
  • 26
  • I am not an angular expert but you cannot access pseudo element with JS so you cannot do it with angular – Temani Afif Oct 19 '18 at 15:13
  • Pseudo-elements are not selectable by JS/JQ as they are not DOM elements. Using a class would be optimal. - https://stackoverflow.com/questions/5041494/selecting-and-manipulating-css-pseudo-elements-such-as-before-and-after-usin – Paulie_D Oct 19 '18 at 15:13
  • check this : https://stackoverflow.com/questions/5041494/selecting-and-manipulating-css-pseudo-elements-such-as-before-and-after-usin/49618941#49618941 it may help you find a way – Temani Afif Oct 19 '18 at 15:14

1 Answers1

1

I was presented with the same situation, it's not possible to access to ::before or ::after HTML element from elementRef; my solution was to create another DIV within the HTML element that I need to access, to modify it with a directive and change the background of the div that would be the new :: before

Example my directive:

@Directive({selector: '[appPrimaryColor]'})

export class PrimaryColorDirective implements OnInit {

  @Input() backgroundColor = false;

  constructor(
    private elementRef: ElementRef,
    private _renderer: Renderer2,
  ) { }

  ngOnInit() {
    // Set BackgroundColor
    if (this.backgroundColor) {
      this._renderer.setStyle(this.elementRef.nativeElement, 'background-color', COLOR);
    }
  }
}

And in HTML:

<div class="icon">
  <!-- step-ok-effect is the new div-->
  <div
    appPrimaryColor
    [backgroundColor]="true"
    class="step-ok-effect"></div>
    <span class="icon-{{ step.state ? 'check' : step.icon }}"></span>
  </div>
</div>