【问题标题】:ternary operator does not work in angular三元运算符不适用于角度
【发布时间】:2020-07-16 10:02:19
【问题描述】:

我有以下代码,我希望每当列表为空时td 显示一个文本,并且一旦它获得一些元素,就显示element.name 但它仅在列表不为空时才有效(我使用console.log(list) 确保长度为 0)

<table mat-table [dataSource]="list" class=" w-100">
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef>header</th>
    <td mat-cell *matCellDef="let element">
    {{ list.length ? element.name : 'the list is empty' }}
    </td>
  </ng-container>
</table>

问题是,当列表为空时,什么都不会显示,但是只要我在列表中添加一些东西,我就可以看到我添加的元素的名称。 我还尝试在 div 中使用 ngIf,然后使用 else 语句添加另一个 ng-template

【问题讨论】:

  • @LuísRamalho 这不对。 list.length 等于 0 时是假的

标签: javascript html angular angular-material conditional-operator


【解决方案1】:

您将表绑定到list。如果列表为空,则表中有 0 行,并且您的三元表达式永远不会运行。只有当您有一个非空列表时,您的三元表达式才会运行。

改为使用*ngIf 隐藏表格并显示空消息。

<table mat-table [dataSource]="list" class=" w-100" *ngIf="list.length">

  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef>header</th>
    <td mat-cell *matCellDef="let element">
      {{element.name}}
    </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

<p *ngIf="!list.length">
  the list is empty
</p>

并且三元表达式在 Angular 中确实有效。试试这个:

<p>{{list.length ? 'has rows' : 'does not have rows'}}</p>

演示:https://stackblitz.com/edit/angular-at5wet

【讨论】:

    【解决方案2】:

    如果列表始终存在(即使是 0 大小),您应该没有任何问题。如果它可以是未定义的,那么你需要使用可选链。

    {{ list?.length ? element.name : 'the list is empty' }}
    

    【讨论】:

    • 我已经在 TS 文件中声明了列表并且它存在。我可以在ngOnInit登录列表
    猜你喜欢
    • 2015-05-03
    • 1970-01-01
    • 2012-10-08
    • 2017-11-13
    • 1970-01-01
    • 2019-05-22
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多