Search code examples
htmlangularngforangular-ng-if

How to use a variable from ngfor in ngif?


I'm encounter a problem while using a variable from *ngFor inside an *ngIf :

<li *ngFor="let event of enum ; let i = index">
  <textarea pInputTextarea autoResize="autoResize" [(ngModel)]=x[i] placeholder="xxx" formControlName=desc{{i}}></textarea>

  <div class="alert" *ngIf="!rForm.controls['desc'" +{{ i }}+ "].valide">
     {{ i }}
  </div>
</li>

I tried to use ngif alone and it's working fine :

<div class="alert" *ngIf=i> *****</div> 

I am able to see the 0 .. 1 .. 2 .. in the DOM.

What is the proper way to do a concatenation in the template?


Solution

  • <li *ngFor="let event of enum ; let i = index">
      <textarea pInputTextarea autoResize="autoResize" [(ngModel)]=x[i] placeholder="xxx" formControlName=desc{{i}}></textarea>
    
      <div class="alert" *ngIf="!rForm.controls['desc'" + i + "].valide">
         {{ i }}
      </div>
    </li>
    

    I do not need to be enclosed in interpolation directive {{}} because it's not string interpolation which you are trying to achieve. Treat it as a variable and use + as you would in with a normal variable.

    Hope this helps!!