2

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

6
  • Is the just the class attribute changing for the wrapping div or it could be any other element? Commented Jul 17, 2020 at 3:13
  • No. I have updated my question. I want to have some directives in particular div. Commented Jul 17, 2020 at 3:22
  • Are you talking about using one directive if condition1 and the other directive if condition2? Slightly confused about your end goal. I think *ngIf is what you want, but I don't quite know what you're trying to achieve. Commented Jul 17, 2020 at 3:24
  • My actual case is using directive in condition1 and no directive in condition2 Commented Jul 17, 2020 at 3:26
  • It is an interesting question. Can you please explain in detail, what are the two conditions ? Why only through directive ? What is your end exact result ? Commented Jul 17, 2020 at 5:18

3 Answers 3

2

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> 
Sign up to request clarification or add additional context in comments.

1 Comment

sorry that I should be more clear on my question. I have updated it and actually I want to have some directives in particular div.
2

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> 

Comments

1

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> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.