如何在不循环所有内容的情况下获取 Angular2 模板中数组的最后一个元素?
How to get the last element of an array in Angular2 template WITHOUT LOOPING EVERYTHING?
这个问题不是问如何访问像 i, first, last 这样的循环变量,而是如何检索变量并将其设置为模板变量。
这不起作用...
<div #lastElement="arr[arr.length-1]"></div>
所以我实际上需要在组件中创建一个局部变量然后直接绑定它?
我觉得过去我可以用 ng-* 指令做的很多事情都需要在组件中进行硬编码...有点降级 tbh
您不能为模板变量分配任意值。模板变量用于引用元素和指令以及用于结构指令的局部变量。
您可以在模板循环中设置 lastelement
变量。 Angular 会自动将循环中的最后一个元素绑定到最后一个指令。
<div *ngFor="#item of items; #lastElement = last">
// Items go here
</div>
https://angular.io/docs/ts/latest/api/common/NgFor-directive.html
您可以使用布尔关键字 last
,在此示例中:
<div *ngFor="let item of items;let last = last;let first = first;let index = index">
first:{{first}}
index:{{index}}
last:{{last}}
</div>
结果:
first:true index:0 last:false
first:false index:1 last:false
first:false index:2 last:false
first:false index:3 last:true
这个问题不是问如何访问像 i, first, last 这样的循环变量,而是如何检索变量并将其设置为模板变量。
这不起作用...
<div #lastElement="arr[arr.length-1]"></div>
所以我实际上需要在组件中创建一个局部变量然后直接绑定它?
我觉得过去我可以用 ng-* 指令做的很多事情都需要在组件中进行硬编码...有点降级 tbh
您不能为模板变量分配任意值。模板变量用于引用元素和指令以及用于结构指令的局部变量。
您可以在模板循环中设置 lastelement
变量。 Angular 会自动将循环中的最后一个元素绑定到最后一个指令。
<div *ngFor="#item of items; #lastElement = last">
// Items go here
</div>
https://angular.io/docs/ts/latest/api/common/NgFor-directive.html
您可以使用布尔关键字 last
,在此示例中:
<div *ngFor="let item of items;let last = last;let first = first;let index = index">
first:{{first}}
index:{{index}}
last:{{last}}
</div>
结果:
first:true index:0 last:false
first:false index:1 last:false
first:false index:2 last:false
first:false index:3 last:true