Home > Mobile >  Assign and check variable in Template
Assign and check variable in Template

Time:06-02

I am trying to figure out how to set a variable when a certain value/string is found in a ngFor loop, and display a div in the same template when it is found...

When this statement is true in the code below I want the contents of the div above it to be displayed (only one time): *ngIf="item.status == 'NODATA'

So I tried to find out how to set a simple variable and set it to true, and display the div based on this, but I have not succeded.

Any suggestion appreciated... I'm using Angular 12....

  <div *ngIf="someVariable?">
     I want this to be displayed when the *ngIf="item.status == 'NODATA' statement is true
   </div>

    <tr *ngFor="let item of getData.result.uga; let i = index">
      <td>
         <ng-container *ngIf="item.status == 'NODATA';else second">
            NO DATA 
         </ng-container>
         <ng-template #second>
           {{item.status}}
         </ng-template>
      </td>
    </tr>

CodePudding user response:

When you get uga data you can simply check it. For example after loading data to uga in typescript write code below:

if(getData.result.uga.some(r=>r.status === 'NODATA'))
   this.someVariable = true;
else
   this.someVariable = false;

CodePudding user response:

<ng-container *ngFor="let item of getData?.result?.uga; let i = index">
  <div *ngIf="item?.status == 'NODATA'">
    I want this to be displasdyed when the *ngIf="item.status == 'NODATA'
    statement is true
  </div>
  <tr>
    <td>
      <ng-container *ngIf="item.status == 'NODATA';else second">
        NO DATA
      </ng-container>
      <ng-template #second>
        {{item.status}}
      </ng-template>
    </td>
  </tr>
</ng-container>

You can do it. Using for Loop in Parent element. I'm using <ng-container></ng-container

CodePudding user response:

Create a method which return a true when item.status == 'NODATA' and call the method like this

div *ngIf="thatMethod()">
 I want this to be displayed when the *ngIf="item.status == 'NODATA' statement is true
<tr *ngFor="let item of getData.result.uga; let i = index">
  <td>
     <ng-container *ngIf="item.status == 'NODATA';else second">
        NO DATA 
     </ng-container>
     <ng-template #second>
       {{item.status}}
     </ng-template>
  </td>
</tr>
  • Related