0

I wanted to change mat-button type dynamically based on certain conditions. This requires changing an attribute of <button> element dynamically. What is the best way to do that? Below is a stackblitz with basic setup.

https://stackblitz.com/edit/angular-material-change-btn-type

I've seen this post. But there are total 8 button types and I think probably it won't be a good solution to add 8 conditions and bind them to a variable. Is there any better alternative?

Edric
  • 24,639
  • 13
  • 81
  • 91
Mahesh
  • 1,427
  • 2
  • 19
  • 42
  • Possible duplicate of [How to add conditional attribute in Angular 2?](https://stackoverflow.com/questions/36745734/how-to-add-conditional-attribute-in-angular-2) – porgo May 14 '19 at 09:00
  • Not really. There are 8 button types available. And i don't think it would be a good solution to add 8 conditions for them. Instead I am seeking for an option to bind a variable to element itself in the form of attribute – Mahesh May 14 '19 at 09:03
  • This is not supported. https://stackoverflow.com/questions/37489761/angular-2-conditionally-add-attribute-directives – Muhammet Can TONBUL May 14 '19 at 09:05
  • Thanks @MuhammetCanTONBUL. But is there any better approach/work-around to solve this problem? – Mahesh May 14 '19 at 09:07

1 Answers1

3

You should be able to solve this by just changing the button element in your template to:

<button mat-button [ngClass]="selectedButtonType">This Button </button>

I hope that helps!

nullchimp
  • 735
  • 4
  • 13
  • Oh, that's pretty useful. I didn't know that it works with classes as well. Thank you so much for help. – Mahesh May 14 '19 at 10:16