Skip to content

Commit be95411

Browse files
committed
feat(NgFor): $last property support
Makes a new `$last` property available during the loop with a boolean showing if it's the last item in the iteration. closes: angular#3102 Closes angular#3991
1 parent 2384082 commit be95411

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

modules/angular2/src/core/directives/ng_for.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
99
* to the current item from the iterable.
1010
*
1111
* It is possible to alias the `index` to a local variable that will be set to the current loop
12-
* iteration in the template context.
12+
* iteration in the template context, and also to alias the 'last' to a local variable that will
13+
* be set to a boolean indicating if the item is the last one in the iteration
1314
*
1415
* When the contents of the iterator changes, `NgFor` makes the corresponding changes to the DOM:
1516
*
@@ -76,6 +77,10 @@ export class NgFor {
7677
for (var i = 0; i < insertTuples.length; i++) {
7778
this._perViewChange(insertTuples[i].view, insertTuples[i].record);
7879
}
80+
81+
for (var i = 0, ilen = this.viewContainer.length; i < ilen; i++) {
82+
this.viewContainer.get(i).setLocal('last', i === ilen - 1);
83+
}
7984
}
8085

8186
private _perViewChange(view, record) {

modules/angular2/test/core/directives/ng_for_spec.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,25 @@ export function main() {
252252
});
253253
}));
254254

255+
it('should display last item correctly',
256+
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
257+
var template =
258+
'<div><copy-me template="ng-for: var item of items; var isLast=last">{{isLast.toString()}}</copy-me></div>';
259+
260+
tcb.overrideTemplate(TestComponent, template)
261+
.createAsync(TestComponent)
262+
.then((rootTC) => {
263+
rootTC.componentInstance.items = [0, 1, 2];
264+
rootTC.detectChanges();
265+
expect(rootTC.nativeElement).toHaveText('falsefalsetrue');
266+
267+
rootTC.componentInstance.items = [2, 1];
268+
rootTC.detectChanges();
269+
expect(rootTC.nativeElement).toHaveText('falsetrue');
270+
async.done();
271+
});
272+
}));
273+
255274
});
256275
}
257276

0 commit comments

Comments
 (0)