Phil O
Phil O

Reputation: 1668

Angular 4 Conditional styling

I have this html code which works great:

<button class="button-style standard-button button-blue" (click)="onOkClick()"
[ngClass]="{'disabled': !hasUnsavedNotes()}" [disabled]="!hasUnsavedNotes()">
Save and close
</button>

My question is how do I change class="button-style standard-button button-blue" to class="button-style standard-button button-grey" when hasUnsavedNotes() returns false? Or simply how do I change the button back color when its disabled? Thanks.

Upvotes: 6

Views: 13135

Answers (3)

Christian G Fritsch
Christian G Fritsch

Reputation: 578

You can just do this little adjustment:

<button 
    [class.button-blue]="!hasUnsavedNotes()"
    [class.button-grey]="hasUnsavedNotes()"
    class="button-style standard-button" 
    (click)="onOkClick()"
    [disabled]="!hasUnsavedNotes()">
    Save and close
</button>

[class.button-blue]="!hasUnsavedNotes()"

will add button-blue css class when !hasUnsavedNotes()returns true and will remove this class when !hasUnsavedNotes()returns false. Is the same to:

[class.button-grey]="hasUnsavedNotes()"

You can remove the [disabled] directive if you wish.

Here is a helpful list of "tricks" to use in Angular: Angular - Cheat Sheet

Upvotes: 10

Phil O
Phil O

Reputation: 1668

This may not be the best way but this solution worked:

<button *ngIf="hasUnsavedNotes() else disable_button"
    class="button-style standard-button button-blue"
    (click)="onOkClick()"
    [ngClass]="{'disabled': !hasUnsavedNotes()}" 
    [disabled]="!hasUnsavedNotes()">
          Save and close
</button>
<ng-template #disable_button>
    <button class="button-style standard-button button-disabled"
        (click)="onOkClick()"
        [ngClass]="{'disabled': !hasUnsavedNotes()}" 
        [disabled]="!hasUnsavedNotes()">
            Save and close
    </button>
</ng-template>

Upvotes: 0

Manzur Khan
Manzur Khan

Reputation: 2486

[ngClass]="{'button-blue': hasUnsavedNotes(), 'button-grey': !hasUnsavedNotes()}"

Upvotes: 2

Related Questions