Ruben Szekér
Ruben Szekér

Reputation: 1175

Compact code for different lay out of disabled Angular Material buttons

I've been wondering if there's any easy way to change the lay out of a disabled button from Angular Material.

Right now, I do it using a ng-container and a ng-template. This works fine, but as you can see the code is not very compact because the only difference between the two buttons (in essence) is class="disabled" and this class should only be used if the button is disabled. I know there's more difference than just that but that's because I just removed (click) etc. for the disabled button since it isn't used anyway. Same goes for the disabled property on the non-disabled button, there's no point in having it.

                <ng-container *ngIf="disabledNext; else next">
                    <button mat-button class="disabled" type="button" [disabled]="disabledNext">
                        Next
                    </button>
                </ng-container>
                <ng-template #next>
                    <button mat-raised-button (click)="nextDate()" type="button">
                        Next
                    </button>
                </ng-template>

I'm looking for an answer along the lines of this but I'm not sure if that's possible

<button mat-button-raised class="disabledNext ? disabled : ''">Next</button>

OR some kind of CSS selector that works if the disabled property of the button is true

button.disabled { ... }

Upvotes: 0

Views: 233

Answers (1)

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

  1. Conditionally set classes using [class.classname]="condition" syntax
  2. Conditionally set disabled using [attr.disabled]="condition ? true : null"

If the button is disabled, the click handler shouldn't fire, but you could always exit the handler early if the button is set to disabled.

Note: the button will be disabled if disabled attribute is present - even an empty string. Using the null value for the enabled state means the attribute won't get added to the HTML.

<button [class.disabled]="disabled" type="button" 
    [attr.disabled]="disabled ? true : null" (click)="nextDate()">
  Next
</button>

This is a demo for pure Angular.

You can conditionally add the mat-raised-button class if not disabled.

<button mat-button [class.mat-raised-button]="!disabled">
</button>

DEMO: https://stackblitz.com/edit/angular-e8gkca

Upvotes: 1

Related Questions