From a15b6794948984fc6ab38c8cee66ab251472f0ec Mon Sep 17 00:00:00 2001 From: Ted Sander Date: Mon, 14 Sep 2015 14:07:59 -0700 Subject: [PATCH] feat(ng_for): Add Even and Odd variables to ng_for Add even and odd local variables to ng_for to allow developers to style table rows differently and other features. Closes #4181 --- .../angular2/src/core/directives/ng_for.ts | 2 + .../test/core/directives/ng_for_spec.ts | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/modules/angular2/src/core/directives/ng_for.ts b/modules/angular2/src/core/directives/ng_for.ts index 62da35517b..74ac217f51 100644 --- a/modules/angular2/src/core/directives/ng_for.ts +++ b/modules/angular2/src/core/directives/ng_for.ts @@ -90,6 +90,8 @@ export class NgFor implements DoCheck { private _perViewChange(view, record) { view.setLocal('\$implicit', record.item); view.setLocal('index', record.currentIndex); + view.setLocal('even', (record.currentIndex % 2 == 0)); + view.setLocal('odd', (record.currentIndex % 2 == 1)); } static bulkRemove(tuples: RecordViewTuple[], viewContainer: ViewContainerRef): RecordViewTuple[] { diff --git a/modules/angular2/test/core/directives/ng_for_spec.ts b/modules/angular2/test/core/directives/ng_for_spec.ts index 4f9bc1530a..fec85c40cb 100644 --- a/modules/angular2/test/core/directives/ng_for_spec.ts +++ b/modules/angular2/test/core/directives/ng_for_spec.ts @@ -271,6 +271,44 @@ export function main() { }); })); + it('should display even items correctly', + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { + var template = + '
{{isEven.toString()}}
'; + + tcb.overrideTemplate(TestComponent, template) + .createAsync(TestComponent) + .then((rootTC) => { + rootTC.debugElement.componentInstance.items = [0, 1, 2]; + rootTC.detectChanges(); + expect(rootTC.debugElement.nativeElement).toHaveText('truefalsetrue'); + + rootTC.debugElement.componentInstance.items = [2, 1]; + rootTC.detectChanges(); + expect(rootTC.debugElement.nativeElement).toHaveText('truefalse'); + async.done(); + }); + })); + + it('should display odd items correctly', + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { + var template = + '
{{isOdd.toString()}}
'; + + tcb.overrideTemplate(TestComponent, template) + .createAsync(TestComponent) + .then((rootTC) => { + rootTC.debugElement.componentInstance.items = [0, 1, 2, 3]; + rootTC.detectChanges(); + expect(rootTC.debugElement.nativeElement).toHaveText('falsetruefalsetrue'); + + rootTC.debugElement.componentInstance.items = [2, 1]; + rootTC.detectChanges(); + expect(rootTC.debugElement.nativeElement).toHaveText('falsetrue'); + async.done(); + }); + })); + }); }