Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Setting '.mat-progress-bar-fill::after' using document.querySelector

I want to dynamically set the progress bar fill value or Angular Material Progress Bar

I’m able to do this in CSS using:

::ng-deep .mat-progress-bar-fill::after {
  background-color: red;
}

Because the CSS value needs to be dynamically set, I cannot do that within the CSS

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried to use – (document.querySelector('.mat-progress-bar-fill::after') as HTMLElement).style.background = 'green'; but that generates an error of ERROR TypeError: Cannot read properties of null (reading 'style')

It is possible though to use the same code to set the background colour using – (document.querySelector('.mat-progress-bar-buffer') as HTMLElement).style.backgroundColor = 'red';

So the questions seems to be how do I select .mat-progress-bar-fill::after using document.querySelector or at least how do I set the fill bar dynamically from within an Angular component?

>Solution :

The before and after pseudo elements are not in the DOM so Javascript doesn’t know about them. But you can use CSS variables and set those in the actual element and they will get picked up by the pseudo element.

e.g. in the CSS:

::ng-deep .mat-progress-bar-fill::after {
  background-color: var(--bg);
}

and in the JS:

document.querySelector('.mat-progress-bar-buffer).style.setProperty('--bg', 'red');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading