Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Conditional styling

Tags:

angular

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.

like image 542
Phil O Avatar asked Feb 14 '18 18:02

Phil O


2 Answers

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

like image 179
Christian G Fritsch Avatar answered Nov 15 '22 12:11

Christian G Fritsch


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

like image 20
Manzur Khan Avatar answered Nov 15 '22 10:11

Manzur Khan