三元运算符在 angular 中不起作用
ternary operator does not work in angular
我有以下代码,我希望每当列表为空时 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
。
如果列表始终存在(即使大小为 0),您应该没有任何问题。如果它可以是未定义的,那么你需要使用可选链接。
{{ list?.length ? element.name : 'the list is empty' }}
您正在将 table 绑定到 list
。如果列表为空,那么你的 table 中有 0 行,你的三元表达式永远不会是 运行。只有当你有一个非空列表时,你的三元表达式才会 运行。
而是使用 *ngIf
隐藏 table 并显示空消息。
<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>
我有以下代码,我希望每当列表为空时 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
。
如果列表始终存在(即使大小为 0),您应该没有任何问题。如果它可以是未定义的,那么你需要使用可选链接。
{{ list?.length ? element.name : 'the list is empty' }}
您正在将 table 绑定到 list
。如果列表为空,那么你的 table 中有 0 行,你的三元表达式永远不会是 运行。只有当你有一个非空列表时,你的三元表达式才会 运行。
而是使用 *ngIf
隐藏 table 并显示空消息。
<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>