0

I'm trying to make a navigation menu with toggable width value in Angular. In my assets folder, I have a variables.scss file that contains all variables bundled in one file for easy accessibility. my variables.scss looks like so:

//global variables
$globalNavWidth: 250px;

The navigation Angular component has its own stylesheet named navbar.scss which has the width property linked to a variable like so:

.navbar{
width: $globalNavWidth;

my folder structure looks something like this.

my folder structure

I have a button in my navigation that triggers the function 'toggleNavWidth()' on click. Is there any way I can change the global variable $globalNavWidth from this toggleNavWidth() function?

6
  • Refer this enter link description here Commented Apr 2, 2019 at 11:39
  • 3
    SCSS is a pre-processor, which means the value $globalNavWidth is only available during compiling from scss to css. You should use ElementRef to change the navbar css properties at runtime. Commented Apr 2, 2019 at 11:39
  • Check this solution. I think this is what you want. stackoverflow.com/questions/33328347/… Commented Apr 2, 2019 at 11:53
  • @ashish.gd I need the $globalNavWidth in other components as well (to scale them with the changes made to $globalNavWidth) is there a functionality in ElementRef that could fix this? Or should I split off my variables so $globalNavWidth is isolated and I can replace it with a hardcoded value? Commented Apr 2, 2019 at 12:24
  • Since you need application wide css changes based on change in the .navbar css' width property. Please have a look at HostBinding. Also this link will help to understand various options: blog.angular-university.io/angular-host-context Commented Apr 2, 2019 at 12:34

3 Answers 3

0

you do this simply with ngStyle or ngClass directive: https://angular.io/api/common/NgStyle

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

2 Comments

The problem is that I have multiple uses for the $globalNavWidth variable. So if I use ngStyle or Class I'd have to somehow get the new value for my nav width to other components as well.
You cant change the scss variable. So maybe you store the width in a service.
0

if u want to apply conditionally apply a CSS class to the element go with [ngClass]:https://angular.io/api/common/NgClass or else if u want to apply a style using class go with:https://angular.io/api/common/NgStyle

Comments

0

I was able to resolve my issue using Host Binding like ashish.gd suggested. The other answers regarding the use of ngStyle or ngClass would have worked for me if not for the fact that the variable is shared among multiple scss files. Thanks for the help everybody!

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.