Angular 4 Conditional styling

Phil O Source

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.

angular

Answers

answered 6 months ago Manzur Khan #1

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

answered 6 months ago Phil O #2

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>

answered 6 months ago Christian G Fritsch #3

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

comments powered by Disqus