2

I have a material button mat-stroked-button as the following:

<button mat-stroked-button color="accent" class="mat-login-header">Login</button>

I need if the user uses a smaller screen size or resolution (such as mobile screen) the button changes its type to mat-button, so in the component constructor I am trying:

constructor() {
  if(document.body.clientWidth < 600) {
    //how to change the button from mat-stroked-button to mat-button?
  }
}

So how can I change it to mat-button if document width is less than 600 and otherwise keep it mat-stroked-button

Khaled
  • 345
  • 5
  • 14
  • 2
    what about creating two blocks of buttons and change which one is visible with a *ngIf based on a variable, smallUI for example? – hamilton.lima Aug 26 '18 at 21:24
  • 2
    My first guess was to do `[attr.mat-stroked-button]="condition"` unfortunately it does not seem to work. So I suggest you to use @hamilton.lima 's solution. – Ploppy Aug 26 '18 at 21:39
  • @Ploppy That's because the `mat-stroked-button` is declared as a directive. – Edric Aug 27 '18 at 07:06

2 Answers2

3

A straightforward way to do it would be create a variable (e.g., useStroked) and then use *ngIf with the two different Material button components:

<button *ngIf="useStroked" mat-stroked-button color="accent" class="mat-login-header">Login</button>
<button *ngIf="!useStroked" mat-button color="accent" class="mat-login-header">Login</button>

You will then need to set that variable in your TS class (for an example see this answer).

I created a sample StackBlitz here.

nick
  • 1,880
  • 17
  • 27
0

Right now. Using two buttons with *ngIf is obsolete. You can use the class to style your buttons instead of the directive. With that said, the following line works.

<button mat-button [ngClass]={"mat-stroked-button": isScreenSmall} color="accent" class="mat-login-header">Login</button>

isScreenSmall is a boolean variable that indicates if the screen size is mobile.

Shan Surat
  • 304
  • 4
  • 13