skip to Main Content

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 possile.

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

2

Answers


  1. 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>
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search