angularangular-materialangular15angular-material-15

Angular Material attribute binding for button classes


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


Solution

  • 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.