Search code examples
angularngforangular-ng-if

How to choose HTML according to the value while using ngFor in angular4?


i am new to angular, suppose i have an array of values like this

domElement:Array<boolean>=[true,false,false,false,false,true,true,true];

and i want different html for true values and different html for false values while using ngFor, I followed this blog and implemented this but it is not working

ie.

     <div *ngFor="let n of domElement; let i=index">   

<div *ngFor="let n of num; let i=index">

    <ng-template *ngIf="n; then gotValue else noValue"></ng-template>

    <ng-template #noValue>
        <div class="alert alert-warning">
            no value found - dummy element for no record !!!
        </div>
    </ng-template>
    <ng-template #gotValue>
        <div class="alert alert-success">
            got values !!!
        </div>
    </ng-template>
</div>

Solution

    1. If you want different code for only two specific case scenerio then you have to use. *ngIf / else not *ngIf / then / else. Explanation here

    <div *ngFor="let n of num"> <template1 *ngIf="n%2 === 0; else other_content"></template1> <template2 #other_content></template2> </div>

    1. If your code doesn't change and only thing that changes is styling than is better to use one common component with style replacement by ng class directive.

    <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>