Check out our Angular Book Series.

How do I switch between different NG Material Button Types?

ng-materal provides a bunch of button variants. Each button type is an HTML button that offers identical functionality, but with slightly different designs and colors. Here is an example of two buttons:

<button mat-flat-button>My Button 1</button>
<button mat-stroked-button>My Button 2</button>

If you drill into the button class, you'll see that all the button variants are implemented in the same code base, as directives.

I was doing a code review on a current project and saw that the code was conditionally determining which button type to display:

<button mat-flat-button *ngIf="condition">My Button 1</button>
<button mat-stroked-button *ngIf="!condition">My Button 1</button>

I was bugged by the fact that we were implementing two button components in our code for what was essentially a style change. That's when I started digging into the specific implementation and discovered that the primary difference between a mat-flat-button and a mat-stroked-button was style changes.

I proposed this alternate approach:

<button mat-button [ngClass]="condition?'mat-flat-button':'mat-stroked-button'">My Button 1</button>

We use the ngClass directive to conditionally flip the style between the flat-button and the stroked-button. It solved our issue with less code.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version