How to wrap a element by different div conditionally in Angular

Viewed 809

Lets say I have a element tree and I want to wrap it in different div based on a condition eg.

//condition == 1
<div class="condition1" condition1Directive>
   <div> ... </div>   //same content
</div>

//condition == 2
<div class="condition2">
   <div> ... </div>   //same content
</div>

I would like to find the most elegant and efficient way to do this in angular. Thanks

3 Answers

If you are looking to just enclose divs with different styling properties you can use ngClass

<div [ngClass]="{'condition1': condition === 1, 'condition2': condition === 2}"> 


<div> ... </div>   //same content

</div>

For using conditional directive you can do something like this:

 <ng-container *ngTemplateOutlet="condition1 === true ? template1 : template2">

<ng-template #template1 directive> <ng-template>

<ng-template #template2></ng-template>

Use *ngIf for the parent div, extract the same content div to a ng-template or component if necessary.

You can check this thread for more detail:

Apply a directive conditionally

<div *ngIf="isCondition1" condition1Directive>
  <sameContentComponent></sameContentComponent>
</ng-container>

<div *ngIf="!isCondition1">
  <sameContentComponent></sameContentComponent>
</ng-container>

You can do like this ways ..

CASE 1

<div *ngIf="condition1" class="condition1" condition1Directive>
   <div> ... </div>   //same content
</div>

<div *ngIf="condition2" class="condition2">
   <div> ... </div>   //same content
</div>

CASE 2

<div [ngClass]="condition1 == true ? 'condition1' : 'condition2'" condition1Directive>
   <div> ... </div>   //same content
</div>
Related