0

I have a button which when clicked , should change the background colour and the fint colours.Back to default when clicked again.So should change from light to dark mode. The CSS classes are .bgdark and .textlight. These needs to added to the 'mainbody' for dark mode.

     HTML
    <div class="mainbody">
    <button type="submit" class="btn btn-primary">Submit</button>
     </div>
    TS

      export class AppComponent {
       title = 'salesapp';
           ngOnInit(){
                 }
                  }

1 Answer 1

2

You can use binding to class names in order to dynamically add or remove them. You would implement the markup like so:

<div class="mainbody" [class.bgnight]="haveClass">
    <button (click)="haveClass = !haveClass">Submit</button>
</div>

And your component would be like so:

export class AppComponent {
    haveClass = false;
}

Your button will toggle the haveClass boolean each time you click on it, which will add and remove the class from your div as expected.

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

3 Comments

Hi, thank you it has worked. If I have multiple class to bind, i can use ngClass. However how does it work with the click event?
If you want to get more complex you would just swap out the click handler for a function that does more complex logic. Basically each class is tied to a value on your component that is true or false, and you simply toggle those as needed.
Hi, can you please elaborate with code, will be helpful . Thanks

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.