11

Angular2..why and how?

How do I execute the below if condition 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>

3 Answers 3

32

You can use the *ngIf structural directive with the 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 blocks and invert the conditional, like so:

<label *ngIf="j === 0">{{val}}</label>
<label *ngIf="j !== 0" style="color:#000000;font-size:12px;padding-top:5px">{{val}}</label>
Sign up to request clarification or add additional context in comments.

3 Comments

I believe *ngIf="j === 0; else elseBlock" is an Angular4 feature, not working in Angular 2 right? Anyway, that would be the best approach in my opinion: 1. Upgrade to Angular 4. 2. Apply this code.
That is correct. I was not sure which version of Angular OP was using so I provided the answer for the current version of the framework and a fall back. I am leery of the angular2-template tag meaning actually template syntax for version 2.X as the description references Angular2 which is not the correct name of the framework.
Indeed. "Angular 2" doesn't exist no more, now is just Angular for versions 2+, and AngularJs for versions 1.x. :D
10

If you plan on upgrading to Angular 4, you could use the new if / else in template that includes this version. Example:

<div *ngIf="someCondition; else falsyTemplate">
  <h1>Condition Passed!</h1>
</div>

<ng-template #falsyTemplate>
  <h1>Condition Failed!</h1>
</ng-template>

Check the following useful links:

I would personally recommend upgrading to Angular 4.

Comments

0

You can do this in Angular 2 by using 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.

Comments

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.