Search code examples
cssangulartypescriptbindingevent-handling

Binding click event with multiple css style in Angular


How do I bind multiple css class to the click event of Submit button in Angular? On the button submit , the style is suppose to change.

HTML

<div class="mainbody" [ngClass]="getStyle">
    <button (click)="getStyle= !getStyle">Submit</button>
</div>

TypeScript

export class AppComponent {
  style1: boolean = true;
  style2: boolean = true;
}

getStyle()

Solution

  • You can define two different state objects :

    export class AppComponent {
      baseState = {
        style1: true,
        style2: true
      }
      activeState = {
        style1: false,
        style2: false
      }
      active = false;
    }
    

    HTML

    <div class="mainbody" [ngClass]="active ? activeState : baseState">
      <button (click)="active = !active">Submit</button>
    </div>