Last active
December 25, 2016 17:27
-
-
Save jsayol/f3e5e831693481aa9efd167f12cebf0f to your computer and use it in GitHub Desktop.
Monkey patching Angular's ngFor to allow "let item in items" instead of "let items of items"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This directive simply allows to use "let item in items" instead of "let item of items" | |
* with ngFor. Its functionality remains unchanged (that is, it still loops over the iterable's values) | |
* | |
* To use it just import it into your module and add it to its "declarations". | |
*/ | |
import { | |
Directive, TemplateRef, Input, ChangeDetectorRef, ViewContainerRef, | |
IterableDiffers, OnChanges, SimpleChanges | |
} from '@angular/core'; | |
import { NgFor } from "@angular/common"; | |
import { NgForRow } from "@angular/common/src/directives/ng_for"; | |
@Directive({selector: '[ngFor][ngForIn]'}) | |
export class NgForIn extends NgFor implements OnChanges { | |
@Input() ngForIn: any; | |
constructor(viewContainer: ViewContainerRef, | |
template: TemplateRef<NgForRow>, | |
differs: IterableDiffers, | |
cdr: ChangeDetectorRef) { | |
super(viewContainer, template, differs, cdr); | |
} | |
ngOnChanges(changes: SimpleChanges): void { | |
if ('ngForIn' in changes) { | |
this.ngForOf = this.ngForIn; | |
changes['ngForOf'] = changes['ngForIn']; | |
super.ngOnChanges(changes); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment