Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access component variable inside SCSS file Angular 2

Tags:

css

sass

angular

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.

like image 922
João Ghignatti Avatar asked Feb 01 '18 18:02

João Ghignatti


People also ask

Can we use both CSS and SCSS in angular?

With the help of Angular CLI, you can install CSS or SCSS on your project and start working on that in a suitable way. If you are working with the CSS or SCSS in your angular project then it is very easy for you as compared to most other frameworks.

What is .scss file in angular?

In the Angular CLI, all components are self-contained and so are their Sass files. In order to use a variable from within a component's Sass file, you'll need to import the _variables. scss file. One way to do this is to @import with a relative path from the component.


1 Answers

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.

like image 174
João Ghignatti Avatar answered Oct 15 '22 06:10

João Ghignatti