Reputation: 18825
I have a button on my screen where if the user has already added clicked on it, it is a mat-filled-button but if I haven't clicked on it, it is a mat-button
My code looks like this
<button
*ngIf="myVote !== 'UPVOTE'"
mat-button
color="primary"
(click)="onVote('UPVOTE')"
>
UPVOTE
</button>
<button
*ngIf="myVote === 'UPVOTE'"
mat-flat-button
color="primary"
(click)="onVote('NONE')"
>
UPVOTE
</button>
Basically I have two buttons and only one shows. Obviously, this is very ugly.
Is there a way where I can achieve the same outcome with only one button and it conditionally is a mat-flat-button
or a mat-button
based on a set of logic?
Upvotes: 9
Views: 7755
Reputation: 2647
An alternative to the accepted answer would be to use [ngClass]
. Making use of ngClass
gives you more flexibility and control for future changing requirements.
Taking the answer and just modifying it to use ngClass
instead would look like this:
<button
mat-button
[ngClass]="{'mat-flat-button': myVote === 'UPVOTE'}"
color="primary"
(click)="onVote(myVote === 'UPVOTE'? 'NONE' :'UPVOTE')"
>
UPVOTE
</button>
The reason I would recommend this over simply using the [class]
attribute, is it makes it easier if you want to apply new conditions to the button in the future. For example, you want a different mat
class when the upvote is 'NONE'
You can now easily just add to the object and it becomes:
<button
mat-button
[ngClass]="{'mat-flat-button': myVote === 'UPVOTE', 'mat-stroked-button': myVote === 'NONE'}"
color="primary"
(click)="onVote(myVote === 'UPVOTE'? 'NONE' :'UPVOTE')"
>
UPVOTE
</button>
See the documentation for ngClass
here: https://angular.io/api/common/NgClass
Upvotes: 0
Reputation: 22213
Try like this:
<button
mat-button
[class.mat-flat-button]="myVote === 'UPVOTE'"
color="primary"
(click)="onVote(myVote === 'UPVOTE'? 'NONE' :'UPVOTE')"
>
UPVOTE
</button>
See Working Demo
_ I have used raised button the demo for better visibility.
Upvotes: 11
Reputation: 11399
From this answer: https://stackoverflow.com/a/36745752/1471485
You could do something like this:
<button
[attr.mat-button]="myVote !== 'UPVOTE'"
[attr.mat-flat-button]="myVote === 'UPVOTE'"
color="primary"
(click)="onVote()"> <!-- Alternate the vote in the function -->
UPVOTE
</button>
onVote(){
if(this.myVote === 'UPVOTE') this.myVote = 'NONE';
else this.myVote = 'UPVOTE';
}
Upvotes: -1