Search code examples
javascriptangular2-directivesngforng-template

Angular 2 writing structural directive like ngFor, iterableDiffer may be causing errors


Hello I am fairly new to Angular 2, and wanted to write an implementation of ngFor to practice. I found this tutorial: https://teropa.info/blog/2016/03/06/writing-an-angular-2-template-directive.html

I had it working, but recently I keep getting this error. "ERROR TypeError: this._trackByFn is not a function".

I wish could debug this more but the documentation is very little, and I don't completely understand the IterableDiffer(s). All see it's dieing after line 41. I've been trying to figure out what I change for several hours now.

let changes = this.differ.diff(this.collection);

Here is the plunk: http://plnkr.co/edit/aM8Wdz72gu7BVNAN9Ulv?p=preview

Thanks for any help offered.

UPDATE:

I found out that I can get my directive to work if I run it in Angular 2, and take out the typing of differ, like this:
private differ:IterableDiffer(now)
private differ:IterableDiffer<any>(before)

Still not a solution because I would like to figure out how I can make this work in Angular 4.


Solution

  • I suspect the problem is upstream of the point where you diff the collection. Angular 4 removed the ChangeDetectorRef parameter for the IterableDifferFactory. I would suggest going back to your Angular 4 version and changing the line of code where you get your differ from something like:

    this.differ = this.differs.find(coll).create(this.changeDetector);
    

    to something like:

    this.differ = this.differs.find(coll).create((value) => value);
    

    I made that change on my custom version of ngFor and that allowed it to work in Angular 4.