X Tutup
Skip to content

Commit ccff175

Browse files
gionkunzalxhub
authored andcommitted
feat(ngFor): Support convenience view local in ngFor
Closes #8013
1 parent fb2773b commit ccff175

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ import {BaseException} from "../../facade/exceptions";
2626
* `NgFor` provides several exported values that can be aliased to local variables:
2727
*
2828
* * `index` will be set to the current loop iteration for each template context.
29+
* * `first` will be set to a boolean value indicating whether the item is the first one in the
30+
* iteration.
2931
* * `last` will be set to a boolean value indicating whether the item is the last one in the
3032
* iteration.
3133
* * `even` will be set to a boolean value indicating whether this item has an even index.
@@ -126,6 +128,7 @@ export class NgFor implements DoCheck {
126128

127129
for (var i = 0, ilen = this._viewContainer.length; i < ilen; i++) {
128130
var viewRef = <EmbeddedViewRef>this._viewContainer.get(i);
131+
viewRef.setLocal('first', i === 0);
129132
viewRef.setLocal('last', i === ilen - 1);
130133
}
131134

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,25 @@ export function main() {
298298
});
299299
}));
300300

301+
it('should display first item correctly',
302+
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
303+
var template =
304+
'<div><copy-me template="ngFor: var item of items; var isFirst=first">{{isFirst.toString()}}</copy-me></div>';
305+
306+
tcb.overrideTemplate(TestComponent, template)
307+
.createAsync(TestComponent)
308+
.then((fixture) => {
309+
fixture.debugElement.componentInstance.items = [0, 1, 2];
310+
fixture.detectChanges();
311+
expect(fixture.debugElement.nativeElement).toHaveText('truefalsefalse');
312+
313+
fixture.debugElement.componentInstance.items = [2, 1];
314+
fixture.detectChanges();
315+
expect(fixture.debugElement.nativeElement).toHaveText('truefalse');
316+
async.done();
317+
});
318+
}));
319+
301320
it('should display last item correctly',
302321
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
303322
var template =

0 commit comments

Comments
 (0)
X Tutup