Angular 14 styling pseudo elements using CSS variables

Viewed 20

I have a radio button that I want to style and I am trying to style pseudo elements using CSS variables in Angular. But I am not seeing any changes. What I have done:

radio.component.html

<label>
    <input type="radio" [attr.name]="radioGroupName" />
    <span [ngStyle]="{'--my-var': 'inset 0 0 0 0.125em #212121'}"></span>
</label>

My TS file

import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnInit, SimpleChanges } from '@angular/core';


@Component({
    selector: 'app-radio-button',
    templateUrl: './radio-button.component.html',
    styleUrls: ['./radio-button.component.scss'],
    // changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RadioButtonComponent implements OnInit {
    @Input() radioGroupName: any;
    constructor(private _changeDetector: ChangeDetectorRef) { }
    ngOnInit(): void {
    }


}

My radio.component.scss file

label span:before {
    display: flex;
    flex-shrink: 0;
    content: "";
    background-color: #fff;
    width: 1.5em;
    height: 1.5em;
    border-radius: 50%;
    margin-right: 0.375em;
    transition: 0.25s ease;
    --my-var: inset 0 0 0 0.125em #00005c;
    box-shadow: var(--my-var);
}

Is it not possible to style pseudo elements in Angular anymore? Thanks!

1 Answers

Instead of initializing CSS variable inside span:before pesduo selector initialize inside parent element

label{
  --my-var: inset 0 0 0 0.125em #00005c; 
} 

Then use style attribute binding to change CSS variable dynamically

<label>
    <input type="radio" [attr.name]="radioGroupName" />
    <span [style.--my-var]="'inset 0 0 0 0.125em #212121'"></span>
</label>

Sample Working Example

Related