Angular ngIf working in a ngFor and I would like to understand why

92 views Asked by At

I am coding a small angular app where the user choose a movie and add it to his favorite list. The favorite list is then displayed and each selected movie has a button to show/hide a div where the movie plot is displayed.

this is my html:

<div *ngFor="let favMovie of favMovies; index as index" class="">
    <div class="card m-2" style="width: 12rem;">
        <img class="card-img-top" src="{{favMovie.poster}}" alt="Card image cap">
        <div class="card-body">         
            <button class="btn btn-sm btn-outline-primary mb-2" (click)="showPlot(index)">Plot</button>         
          <div class="text-center">
          <h5 class="card-title"><b>{{favMovie.title}}</b></h5>
          </div>
          <div *ngIf="showPlotValue[index]">
             <p class="card-text">{{favMovie.plot}}</p>
          </div>
        </div>    
      </div>
</div>

and my component.ts

export class MovieListComponent implements OnInit {

  @Input() favMovies: any;  
  
  showCastValue= [false]
  showPlotValue= [false]
  

  
  showPlot(index: number) {    
    this.showPlotValue[index] = !this.showPlotValue[index];
  };
} 

The weird things is that's it working. How can it be since since as declare showCastValue as an array with a single value and I can access this.showPlotValue[index] for index higher than one?

1

There are 1 answers

1
Abdelmlak Dhif On
 *ngIf="showPlotValue[index]" 

is not testing on true/false when there is no value ! its testing on the existence of the value : if there is no value then it would return false (however if there is a value it will test it whether its true or false) Check Truthy vs true and falsy vs false. this article should help you .

https://howtodoinjava.com/typescript/truthy-and-falsy/