15

Is it possible to access a component variable inside .scss file defined for that component?
Ex:

example.component.ts

@Component({
  selector: 'example-selector',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css']
})
export class ExampleComponent {
  @Input() size: number;
}

example.component.scss

.some-class {
  width: calc(100% - {{ size }};
}

If not, how would be a good work around?

Thanks.

3
  • 4
    no, its not possible Commented Feb 1, 2018 at 19:02
  • 1
    I will add to @Jota.Toledo 's comment that SCSS is compiled to pure CSS which is static, there is no variables. Commented Feb 1, 2018 at 19:21
  • Is there nowadays any update for this issue? Commented May 20, 2021 at 5:58

1 Answer 1

17

Oukei, the solution I found to work around that is actually simple and it does let you use component variables inside styles.
You basically use [ngStyle] directive to change the property of an element.

example.component.ts

@Component({
  selector: 'example-selector',
  templateUrl: 'example.component.html',
  styleUrls: ['example.component.css']
})
export class ExampleComponent {
  @Input() size: number;
}

example.component.html

<div [ngStyle]="{ 'width': 'calc(100% - ' + size + 'px)' }"></div>

or you can use calc to divide with

<div [ngStyle]="{ 'width': 'calc(100% / ' + size + ')' }"></div>

or use any other given property like that.
And you can also have classes defined for that element and have a specific (or multiple) properties defined with ngStyle.

Thanks.

Sign up to request clarification or add additional context in comments.

1 Comment

The limitation of this approach is css pseudo-elements :before, :after that are not accessible in html

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.