iamjoshua
iamjoshua

Reputation: 1269

How to dynamically change the styles in the class to be used in Angular 6?

As of the moment, I could already change design of the buttons by using ng-container. A snippet of that code is below.

  <ng-container *ngIf="isDisabled;">
        <button class="bot-btn-disabled"
                (click)="confirm()"
                [disabled]=this.isDisabled >
          Confirm
        </button>
  </ng-container>

  <ng-container *ngIf="!isDisabled;">
    <button class="bot-btn"
            (click)="confirm()"
            [disabled]=this.isDisabled >
      Confirm
    </button>
  </ng-container>

However, this seems to long for , as I just need to change the class="bot-btn" of my button that if isDisabled = false, it will change to that style which is bot-btn and vice versa. Is there any way of doing this the shorter way?.

Upvotes: 2

Views: 227

Answers (2)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24424

ngClass directive can accept an object where keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed .

  <button 
        [ngClass]="{'bot-btn-disabled': this.isDisabled ,'bot-btn' : !this.isDisabled " } 
        (click)="confirm()"
        [disabled]=this.isDisabled >
              Confirm
   </button>

others values ngClass accept are string or array check the demo in the 👉 documentation page

Upvotes: 1

XardasLord
XardasLord

Reputation: 1937

You can set the class on your button based on the condition like this:

[ngClass]="this.isDisabled ? 'bot-btn-disabled' : 'bot-btn'"

Upvotes: 3

Related Questions