Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic, Angular - ChangeDetectorRef is undefined

I am importing the ChangeDetectorRef like so:

import { Component, ViewChild, ChangeDetectorRef , ElementRef } from '@angular/core';

And initializing a change detector in the constructor of my page like so:

constructor(
    ...
    private ref: ChangeDetectorRef
  )

But when I execute detectChanges() in a callback function:

 hardResetCallback(car:Car){
    this.car=car;
    this.ref.detectChanges();
  }

It says "Can't read property 'detectChanges' of undefined". What could I be missing?

EDIT:

The callback is called from a modal. The modal gets the callback through nav params - in the parent component I call:

const resetModal : Modal = this.modal.create('CarConfigurationResetPage', { car: this.car, callback: this.hardResetCallback });
    resetModal.present();

And then this is how I get it in the modal:

 this.callback=this.navParams.get('callback');

I call the callback from the modal in the success method of an AJAX call like this:

this.callback(response);
like image 511
gfels Avatar asked Jul 19 '18 08:07

gfels


1 Answers

 hardResetCallback = (car:Car) => {
    this.car=car;
    this.ref.detectChanges();
  }

Use fat arrow function to prevent creation of “this” inside the scope of your hardResetCallback method.

See more about arrow functions here.

Relevant quote:

"In classic function expressions, the this keyword is bound to different values based on the context in which it is called. With arrow functions however, this is lexically bound. It means that it uses this from the code that contains the arrow function."

like image 82
Sergey Rudenko Avatar answered Oct 13 '22 01:10

Sergey Rudenko