el_pup_le
el_pup_le

Reputation: 12189

null property for component after ChangeDetectorRef detectChanges()

Why is the component null after changeDetector is called?

@HostListener('window:resize', ['$event'])
onResize(event) {
    clearTimeout(this.resizeTimer);
    this.resizeTimer = setTimeout(this.resizeObj(), 500);
}

resizeObj() {
    this.applyUpd(this.dataList);
    this.changeDetector.detectChanges();
}



applyUpd(dataList: Data[]) {

    for (var i = 0; i < this.dataList.length; i++) {
        this.dataList[i].applyData(this.width, this.height);
    }        

}

Constructor

constructor(private changeDetector: ChangeDetectorRef) {        
        this.resizeTimer;
        this.route.data
            .subscribe(( data: { dataList: Data[] }) => {
                // ...
            });
    }

Error:

core.es5.js:1084 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'dataList' of null
TypeError: Cannot read property 'dataList' of null
    at Object.eval [as updateDirectives] (DataListComponent.html:7)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:12806)
    at checkAndUpdateView (core.es5.js:12144)
    at callWithDebugContext (core.es5.js:13206)
    at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.es5.js:12746)
    at ViewRef_.detectChanges (core.es5.js:10218)
at DataListComponent.webpackJsonp.151.DataListViewComponent.applyUpd(data-list-view.component.ts:73)
    at SafeSubscriber._next (data-list.component.ts:55)
    at SafeSubscriber.__tryOrSetError (Subscriber.js:247)
    at SafeSubscriber.next (Subscriber.js:187)
    at Object.eval [as updateDirectives] (DataListComponent.html:7)

Upvotes: 1

Views: 1674

Answers (1)

Zebulon Li
Zebulon Li

Reputation: 540

the error is in onResize(event) method. You call this.changeDetector.detectChanges() before the component init.

change

this.resizeTimer = setTimeout(this.resizeObj(), 500);

to

this.resizeTimer = setTimeout(this.resizeObj, 500);

Upvotes: 1

Related Questions