Home > OS >  Conditionally wrap an element
Conditionally wrap an element

Time:10-08

I have some html I'd like to wrap if a condition it true.

Here's the element:

<a mat-button color="accent" [routerLink]="record.id">
  {{record[column.name]}}
</a>

I'd like to wrap it like this:

  <span matBadge="New" matBadgeOverlap="true"> 
    <a mat-button color="accent" [routerLink]="record.id">
      {{record[column.name]}}
    </a>
  </span>

Here's what I tried:

{{ value1 > vlaue2 &&
  <span matBadge="New" matBadgeOverlap="true"> 
}}
    <a mat-button color="accent" [routerLink]="record.id">
      {{record[column.name]}}
    </a>
{{ value1 > value2 && 
  </span>
}}

I feel this is probably not best practice

CodePudding user response:

You can try this solution using *ngIf statement to handle it:-

<span>
 <a mat-button color="accent" [routerLink]="record.id" *ngIf="!(value1 > vlaue2)">
      {{record[column.name]}}
    </a>

<span matBadge="New" matBadgeOverlap="true" *ngIf="value1 > vlaue2"> 
    <a mat-button color="accent" [routerLink]="record.id">
      {{record[column.name]}}
    </a>
  </span>
</span>

By using ngIf you can render html section as per expression value.

CodePudding user response:

Use a conditional template like this to display the content within a span, otherwise display it without:

<span *ngIf="value1 > value2; else falseCondition" 
    matBadge="New" matBadgeOverlap="true">  
    <a mat-button color="accent" [routerLink]="record.id">
      {{record[column.name]}}
    </a>
</span>
<ng-template #falseCondition>
    <a mat-button color="accent" [routerLink]="record.id">
      {{record[column.name]}}
    </a>
</ng-template>
  • Related