Home > OS >  How to add css class styles on button click in Angular?
How to add css class styles on button click in Angular?

Time:07-18

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 >
    <button type="submit" >Submit</button>
     </div>
    TS

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

CodePudding user response:

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

<div  [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.

  • Related