If else in angular2 template syntax

Angular2 .. why and how?

How to fulfill if condition below in angular2

<td *ngFor="let val of rows;let j=index"> IF J==0 <label>{{val}}</label> ELSE: <label style="color:#000000;font-size:12px;padding-top: 5px">{{val}}</label> </td> 
+8
angular angular2-template
source share
3 answers

You can use the * ngIf structured directive with if-else syntax to achieve this result.

 <label *ngIf="j === 0; else elseBlock">{{val}}</label> <ng-template #elseBlock> <label style="color:#000000;font-size:12px;padding-top: 5px">{{val}}</label> </ng-template> 

Another option is to use two *ngIf and invert the conditional expression, for example:

 <label *ngIf="j === 0">{{val}}</label> <label *ngIf="j !== 0" style="color:#000000;font-size:12px;padding-top:5px">{{val}}</label> 
+18
source share

If you plan to upgrade to Angular 4, you can use the new if / else template, which includes this version. Example:

 <div *ngIf="someCondition; else falsyTemplate"> <h1>Condition Passed!</h1> </div> <ng-template #falsyTemplate> <h1>Condition Failed!</h1> </ng-template> 

Check out the following useful links:

I personally would recommend switching to Angular 4.

+5
source share

You can do this in Angular 2 with the <ng-container> element. In your example, it should be something like this:

 <td *ngFor="let val of rows;let j=index"> <ng-container *ngIf="J==0"> <label>{{val}}</label> </ng-container> <ng-container *ngIf="J!=0"> <label style="color:#000000;font-size:12px;padding-top: 5px">{{val}} </label> </ng-container> </td> 

You can find more information in the docs: https://angular.io/guide/structural-directives#ng-container-to-the-rescue .

0
source share

All Articles