Angular ngIf 在 ngFor 中工作,我想了解为什么

问题描述

我正在编写一个小角度应用程序,用户可以在其中选择一部电影并将其添加到他最喜欢的列表中。然后显示收藏夹列表,每个选定的电影都有一个按钮show/hide 显示电影情节的 div。

这是我的 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>

和我的 component.ts

export class MovieListComponent implements OnInit {

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

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

奇怪的是它确实有效。怎么会因为 as 将 showCastValue 声明为具有单个值的数组并且我可以访问 this.showPlotValue[index]获取大于 1 的索引?

解决方法

 *ngIf="showPlotValue[index]" 

当没有值时不测试真/假!它对值是否存在的测试:如果没有值,那么它将返回 false(但是,如果有一个值,它将测试它是真还是假)检查真与真和假与假。这篇文章应该对你有所帮助。

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