简体   繁体   中英

How do I conditionally add mat-raised-button?

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?

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.

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

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';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM