|
| 1 | + |
| 2 | +// Import the core angular services. |
| 3 | +import { Directive } from "@angular/core"; |
| 4 | +import { DoCheck } from "@angular/core"; |
| 5 | +import { Input } from "@angular/core"; |
| 6 | +import { NgForOf } from "@angular/common"; |
| 7 | +import { NgForOfContext } from "@angular/common"; |
| 8 | +import { NgIterable } from "@angular/core"; |
| 9 | +import { OnChanges } from "@angular/core"; |
| 10 | +import { TemplateRef } from "@angular/core"; |
| 11 | +import { TrackByFunction } from "@angular/core"; |
| 12 | + |
| 13 | +// ----------------------------------------------------------------------------------- // |
| 14 | +// ----------------------------------------------------------------------------------- // |
| 15 | + |
| 16 | +@Directive({ |
| 17 | + selector: "[ngPureFor][ngPureForOf]" |
| 18 | +}) |
| 19 | +export class NgPureForDirective<T> extends NgForOf<T> implements OnChanges, DoCheck { |
| 20 | + |
| 21 | + // This directive is really a very very very thin wrapper around the existing NgForOf |
| 22 | + // directive. It's using all the inherited functionality; only, it needs to alias |
| 23 | + // the input bindings since we're using a slightly different selector "ngPureFor". |
| 24 | + // And, since the native NgForOf directive uses the @Input() decorator, we need to |
| 25 | + // use it as well in order to setup the aliases. |
| 26 | + |
| 27 | + @Input( "ngPureForOf" ) |
| 28 | + public ngForOf!: NgIterable<T>; |
| 29 | + |
| 30 | + @Input( "ngPureForTrackBy" ) |
| 31 | + public ngForTrackBy!: TrackByFunction<T>; |
| 32 | + |
| 33 | + @Input( "ngPureForTemplate" ) |
| 34 | + public ngForTemplate!: TemplateRef<NgForOfContext<T>>; |
| 35 | + |
| 36 | + // --- |
| 37 | + // PUBLIC METHODS. |
| 38 | + // --- |
| 39 | + |
| 40 | + // I get called whenever change-detection is triggered. |
| 41 | + public ngDoCheck() : void { |
| 42 | + |
| 43 | + // In the native NgForOf directive, the Differ for the NgForOf collection is |
| 44 | + // checked on every change-detection digest. However, since we're turning this |
| 45 | + // into a "pure" directive (so to speak), we want to override the ngDoCheck() |
| 46 | + // method such that IT DOES NO WORK during arbitrary change-detection digests. |
| 47 | + |
| 48 | + } |
| 49 | + |
| 50 | + |
| 51 | + // I get called whenever one of the input bindings is changed. |
| 52 | + public ngOnChanges() : void { |
| 53 | + |
| 54 | + // The ngOnChanges() method will be called if the ngForOf, ngForTrackBy, or |
| 55 | + // ngForTemplate input bindings get changed. Since this is when we want to |
| 56 | + // actually perform our internal change-detection test, we can now turn around |
| 57 | + // and call the inherited ngDoCheck() method (on SUPER). This will inspect the |
| 58 | + // Differ and update the template rendering. |
| 59 | + super.ngDoCheck(); |
| 60 | + |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments