1

Is there any way to access the TypeScript variables in my SCSS code in my Angular component?

I want to do something like this:

<style type="text/css">
  .source-status-{{ event.status.id }}::before {
    border-left: 20px solid {{ event.status.color }};
  }
</style>

<div class="source-status-{{ event.status.id }}">
  ...
</div>

Is there any way to set CSS property of a ::before pseudo element in Angular component?

1
  • exactly what I need! good question Commented Sep 29, 2023 at 10:29

2 Answers 2

1

I don't think it's possible, cause SCSS is compiled into CSS when you build your app, so there can't be any dynamic values.
You can try to use CSS variables, but you should change the way you create class names. You can add variables to style attribute of your component like:

@HostBinding('attr.style')
  public get cssVariables(): SafeStyle {
    LOGIC TO DEFINE VARIABLE VALUE
    const cssVariables = `
      --my-variable: value
    `;
    return this.sanitizer.bypassSecurityTrustStyle(cssVariables);
  }

And in your SCSS file you can use this variables:

.source-status-{{--you-should-think-of-static-class-names--}}::before {
    border-left: 20px solid var(--my-variable);
  }
Sign up to request clarification or add additional context in comments.

1 Comment

probably the best answer in the world! deserves much more upvotes - I didn't have to use DomSanitizer to get this working
0

I found a workaround. Not a nice way, but it's working.

In the .ts file:

html = '.' + event.status.id + '::after { border-left-color:' + event.status.color + ' !important; } ';

const style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = html;
document.getElementsByTagName('head')[0].appendChild(style);

Then in the HTML file:

<div class="color-{{ event.status.id }}">
  ...
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.