[英]ngIf can reference variable in nested ngFor in Angular 1.5. How to achieve the same in Angular 10?
The following code works in Angular 1.5.以下代码适用于 Angular 1.5。 The <tr> element will only be rendered if the 'showFields' flag for that row key is enabled.
<tr> 元素只有在启用了该行键的 'showFields' 标志时才会呈现。
<table>
<ng-container *ngIf="showFields[row.key]">
<tr *ngFor="let row of rows">
<td>{{row.key}}</td>
<td>{{row.value}}</td>
</tr>
</ng-container>
</table>
Note that the 'row' variable from the ngFor is visible to the enclosing ngIf.请注意,来自 ngFor 的“行”变量对封闭的 ngIf 是可见的。 This no longer works in Angular 2+ because the scope of the ngFor variable is now confined to the element.
这不再适用于 Angular 2+,因为 ngFor 变量的 scope 现在仅限于元素。 How could I achieve the same effect?
我怎样才能达到同样的效果?
You could just switch the ngFor
and ngIf
, like so:您可以像这样切换
ngFor
和ngIf
:
<table>
<ng-container *ngFor="let row of rows">
<tr *ngIf="showFields[row.key]">
<td>{{row.key}}</td>
<td>{{row.value}}</td>
</tr>
</ng-container>
</table>
Instead of using a separate showFields
boolean array, you could also think about adding a new property showField to the row object, then you can simply check *ngIf="row.showField"
, which prevents out of bounds exceptions.除了使用单独的
showFields
boolean 数组,您还可以考虑将新属性 showField 添加到行 object,然后您可以简单地检查*ngIf="row.showField"
,这可以防止越界异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.