0

I would like to assign a property to an html tag in angular based on a given condition. For example:

<button 
    {{condition === true ? mat-raised-button : mat-button}}
    class="edit-button"
>
  <span>Click here</span>
</button>

The code above doesn't work. A valid way to achieve my goal would be:

<div class="wrapper" *ngIf="condition === true; else regular">
  <button 
      mat-raised-button
      class="edit-button"
  >
    <span>Click here</span>
  </button>
</div>
<ng-template #regular>
  <button 
      mat-button
      class="edit-button"
  >
    <span>Click here</span>
  </button>
</ng-template>

But as you can see there's a lot of repeated code above and I would like to do it in a nicer way, if possible.

I would like to assign an html property based on a given condition. And I would like to do it in an elegant way.

André
  • 1,602
  • 2
  • 12
  • 26
  • Does this answer your question? [Apply a directive conditionally](https://stackoverflow.com/questions/44597077/apply-a-directive-conditionally) – Philipp Meissner Apr 03 '23 at 12:00
  • Yes agree! a Duplicate of https://stackoverflow.com/questions/44597077/apply-a-directive-conditionally – Satsangpriyadas Swami Apr 03 '23 at 12:07
  • I couldn't find this answer when I asked my question. However, as I already mentioned in my question the `*ngIf / ng-template` solution proposed doesn't look that nice and I'm looking for something more elegant. – André Apr 03 '23 at 12:10

2 Answers2

0

I can see that your are looking for class css condition You can try :

[ngClass]="{'my_class': condition1, 'my_class2' : condition2 }"

Exemple :

<button 
    [ngClass]="{'mat-raised-button': condition , 'mat-button' : !condition  }"
    class="edit-button"
>
  <span>Click here</span>
</button>
DEV
  • 1,607
  • 6
  • 19
0

You cannot apply angular directives conditionally you'll have to use ng-template for this:

<ng-container *ngIf="condition; else #regular">
  <button mat-raised-button>…</button>
</ng-container>
<ng-template #regular>
  <button mat-button> … </button>
</ng-template>

To have it working for all possible variants given by Angular Material you should check the ngTemplateOutlet docs

Some random IT boy
  • 7,569
  • 2
  • 21
  • 47