ngSwitch 在评估为 true 时不显示项目

ngSwitch not showing item when evaluated to true

我不确定我在这里做什么。我在 ngFor

里面有这个 ngSwitch
          <li class="b-inBoxItem" *ngFor="let item of uploader.queue">
                <div [ngSwitch]="item.file.name">
                    <span *ngSwitchCase="item.file.name.includes('.png')" class="ic ic-file-image"></span>
                    <span *ngSwitchCase="item.file.name.includes('.jpeg')" class="ic ic-file-image"></span>
                    <span *ngSwitchCase="item.file.name.includes('.doc')" class="ic ic-file-stats"></span>
                        .
                        .
                        .
                    <span *ngSwitchDefault class="ic ic-file-empty"></span>
                </div>
          </li>

当我查看调试器时,我可以看到第一种情况 .png 被评估为 true:

<!--bindings={
    "ng-reflect-ng-switch-case": "true"
}-->

其余的都判断为false

但是,只显示默认项目。

我做错了什么?

汤姆

ngSwitch指令类似于switch语句。它显示 ngSwitchCase 值等于 ngSwitch 变量的元素。这是取自 this Rangle.io article:

的示例
<div [ngSwitch]="tab">
  <app-tab-content *ngSwitchCase="1">Tab content 1</app-tab-content>
  <app-tab-content *ngSwitchCase="2">Tab content 2</app-tab-content>
  <app-tab-content *ngSwitchCase="3">Tab content 3</app-tab-content>
  <app-tab-content *ngSwitchDefault>Select a tab</app-tab-content>
</div>

在您的例子中,表达式为每个 ngSwitchCase 提供一个布尔值。你最终得到相当于:

<li class="b-inBoxItem" *ngFor="let item of uploader.queue">
  <div [ngSwitch]="item.file.name">
    <span *ngSwitchCase="true" class="ic ic-file-image"></span>
    <span *ngSwitchCase="false" class="ic ic-file-image"></span>
    <span *ngSwitchCase="false" class="ic ic-file-stats"></span>
      .
      .
      .
    <span *ngSwitchDefault class="ic ic-file-empty"></span>
  </div>
</li>

默认显示span,因为item.file.name不等于truefalse


要使其正常工作,请在 ngSwitch 中指定文件扩展名并测试可能的值:

<li class="b-inBoxItem" *ngFor="let item of uploader.queue">
  <div [ngSwitch]="getFileExtension(item.file.name)">
    <span *ngSwitchCase="'png'" class="ic ic-file-image"></span>
    <span *ngSwitchCase="'jpeg'" class="ic ic-file-image"></span>
    <span *ngSwitchCase="'doc'" class="ic ic-file-stats"></span>
      .
      .
      .
    <span *ngSwitchDefault class="ic ic-file-empty"></span>
  </div>
</li>

使用方法(见this post):

getFileExtension(filename: string): string {
  return filename.split('.').pop();
}

另一种解决方案是使用 ngIf:

<li class="b-inBoxItem" *ngFor="let item of uploader.queue">
  <div>
    <span *ngIf="item.file.name.includes('.png')" class="ic ic-file-image"></span>
    <span *ngIf="item.file.name.includes('.jpeg')" class="ic ic-file-image"></span>
    <span *ngIf="item.file.name.includes('.doc')" class="ic ic-file-stats"></span>
      .
      .
      .
    <span *ngIf="!item.file.name.includes('.png') && !item.file.name.includes('.jpeg') && !item.file.name.includes('.doc')" class="ic ic-file-empty"></span>
  </div>
</li>