Angular Material attribute binding for button classes

205 Views Asked by At

I want to render a raised or a strike button in Angular Material - depending on a variable from backend's code behind.

I tried this:

<button
   [attr.mat-raised-button]="this.myValue === false ? '' : null"
   [attr.mat-stroked-button]="this.myValue === true ? '' : null"
   color="primary">
   ButtonTitle
</button>

And magically the correct attribute is set - if I inspect the rendered code. But it isn't "used" or "applied" in someway. Thus, the button looks like it has no attribute set:

enter image description here

But depending on this.myValue the button should look like a one of these buttons:

enter image description here

Demo: https://stackblitz.com/edit/angular-zsnfkb-xcdfqh

2

There are 2 best solutions below

2
Wandrille On BEST ANSWER

To make it short, you can't with ease.

But you can still play with *ngIf to display the desired button.

<button mat-stroked-button
   color="primary" *ngIf="this.myValue === true">
   ButtonTitle
</button>
<button mat-raised-button
   color="primary" *ngIf="this.myValue === false">
   ButtonTitle
</button>

Even better, if you use it often, you can encapsulate the logic into a specific component.

0
magor On

Not sure if this is a valid approach (using [attr.mat-raised-button] ), but using ngIf would surely be a good approach.

Similar to this:

    <div *ngIf="myValue">
      <button mat-raised-button color="primary">
        ButtonTitle
      </button>
    </div>

More details about ngIf here.