0

In vue we can use conditional rendering like this:

<div v-if="condition1">Condition1 is true</div>
<div v-else-if="condition2">Condition2 is true</div>
<div v-else-if="condition3">Condition3 is true</div>
<div v-else>All of the above conditions are false</div>

How can I achive a similar functionality in angular 10?

I know that angular has *ngIf directive but as far as i know we can only achieve if; else with it and no more. I looked around and looks like I will have to implement a directive, but have no clue how to start. Any help is appreciated.

EDIT: Tried using ngSwitch.

<ng-container [ngSwitch]="true">
  <div *ngSwitchCase="true">Condition1 is true</div>
  <div *ngSwitchCase="false">Condition2 is true</div>
  <div *ngSwitchCase="true">Condition3 is true</div>
  <div *ngSwitchDefault>All of the above conditions are false</div>
</ng-container>

Gives:

Condition1 is true
Condition3 is true

Instead of just

Condition1 is true

2 Answers 2

1

You could use a workaround using [ngSwitch] directive with true.

Try the following

<ng-container [ngSwitch]="true">
  <div *ngSwitchCase="condition1">Condition1 is true</div>
  <div *ngSwitchCase="condition2">Condition2 is true</div>
  <div *ngSwitchCase="condition3">Condition3 is true</div>
  <div *ngSwitchDefault>All of the above conditions are false</div>
</ng-container>

Update

You could nest *ngIf directive's else block to achieve a if-else-if like structure.

Try the following

<div *ngIf="condition1; else condition2">Condition 1 is true</div>

<ng-template #condition2>
  <div *ngIf="condition2; else condition3">Condition 2 is true</div>
</ng-template>

<ng-template #condition3>
  <div *ngIf="condition3; else condition4">Condition 3 is true</div>
</ng-template>

<ng-template #condition4>
  <div>Condition 4 is true</div>
</ng-template>
Sign up to request clarification or add additional context in comments.

4 Comments

See edit. This acts more like series of if statements not if-else-if
@RahulRBadenkal: One of the setbacks of the workaround. You could instead try another workaround. I've updated the answer.
It works!. Thanks. Only thing, I think it should be "else condition2" instead of "else #condition2"
@RahulRBadenkal: Overlooked it, I've edited the post.
0

You can use *ngIf="condition; else elseBlock" to achive the same behaviour:

<div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>
<ng-template #elseBlock>Content to render when condition is false.</ng-template>

You can refer to the documentation

1 Comment

Yes it works for simple if-else conditions, but not for multiple if-else-if with say 3 or more else ifs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.