0

Im currently working on a Angular2 application with webpack and Im trying to set differents css themes according to the user.

For example : When the user connect, If it's a boy, I want to have my backgrounds blue, and if it's a girl I want the backgrounds to be pink.

Simply changing the css value with setAttribute or style.property wont work because the DOM is destroyed when changing tab in the application, it needs to be kinda permanent.

I've tried using different css stylesheets (1 for each theme) and linking them to my html with javascript when the user connect. Problem is, webpack is always adding automatically my css to my html when building the app.

Thanks for the help.

1
  • 1
    Have you tried to declare scope var and use ngClass ? Commented Apr 26, 2017 at 15:00

3 Answers 3

4

In your css, make a rule like :

.is-boy{
    background: blue;
}

.is-girl{
    background: pink;
}

and declare in you angular app a scope var like $scope.userSex = 'boy';

and on your body use ngClass like this

<body [ngClass]="{'is-boy': userSex === 'boy', 'is-girl': userSex === 'girl'}" ...
Sign up to request clarification or add additional context in comments.

5 Comments

This looks like its working, would have been better If I could hit all elements at once since I have to put ngClass on 50+ elements :p
@Duncan you don't use sass or less ? ^^
I'm using sass but also WebPack who build the app and convert sass into css, and I need to change the theme while the app is running because I got the information 'isABoy : isAGirl' only when the user connect.
@Duncan just make a new stylesheet and encompass all rules with your class, no ?
@Duncan don't forget to click on the check button on the left if my response solve your problem, thank you
1

:host-context selector

You could use the :host-context selector to apply styles to your component based on the parent component.

styles:[`
    :host-context(.parent1) div{
      border: 1px solid blue;
    }

    :host-context(.parent2) div{
      border: 1px solid blue;
    }
  `]

This allows you to conditionally apply styles based on a the selector that wraps the component.

plunker

edit:

So in your case - your parent would have a div with class .boy and a div with class .girl

You could load these containing divs with some flag controlled by ngIf

Comments

0

If you want to be permanent store class value in localStorage. To set the theme use ngClass with variable set to theme you need.

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.