0

I am facing a quite strange behaviour of my DOM element, by building an application with angular 2.

I am using a canvas element to draw a graph inside of it and I am selecting the element by using @ViewChild. Somehow angular says that it can not further execute any methods because of undefined.

So I logged out exactly before the error occurs.

console.log(this); console.log(this.graphCanvas); The result: enter image description here

Hope you get what I mean. this contains the graphCanvas element but if I try accessing it I got a undefined.

EDIT: I am using a map to draw circles on this map (data viz project). The problem only occurs when I start the application and only if I use the search the first time. Both methods, search and click on circle, head to the same methods.

Click on Circle - working: enter image description here

cityCircle.addListener('click', function (e) {
 localThis.currentCity = cityCircle.data_obj;
    localThis.cityClicked = true
    localThis.zone.run(() => {});
    cityCircle.setOptions({
        fillColor: '#d7490b',
        strokeColor: '#026384'
    });
    if (localThis.currentCircleInMap) {
        localThis.currentCircleInMap.setOptions({
            fillColor: '#026384',
            strokeColor: '#026384'
        });
    }
    localThis.currentCircleInMap = cityCircle;

    localThis.map.setCenter({
        lat: localThis.currentCity.geo_data.lat,
        lng: localThis.currentCity.geo_data.lng
    });
    localThis.map.setZoom(10);
    localThis.setGraphView(localThis.currentCity.data_by_year);
});

Search - not working: enter image description here

autoCompleteClicked(event): void {    
    try {
      var cityClickedKey = event.getAttribute('data-city');
    } catch (error) {
      var cityClickedKey = event.value;
    }

    this.globalData.migration_data.forEach(element => {     
      if (element.city.includes(cityClickedKey)) {        
        this.currentCity = element;
        this.map.setCenter({
          lat: this.currentCity.geo_data.lat,
          lng: this.currentCity.geo_data.lng
        });
        this.map.setZoom(10);
        this.highlightClickedCircle()
        this.cityClicked = true;
      }
    });
    (<HTMLInputElement>document.getElementById("search")).value = this.currentCity.city;
    this.autoCompleteAvailable = false;
    this.setGraphView(this.currentCity.data_by_year);}

In the setGraphView method the element child is not set.

Markus Guder
  • 621
  • 1
  • 5
  • 11
  • 1
    The message by itself is not enough to understand what's going on. Could you add some relevant code? – Vega Aug 24 '17 at 19:05

1 Answers1

1

console.log can only show you the current state of the object, not the object of the snapshot at the time of when it was called.

It prints a reference to the object, and by the time you see it in web devtool, it's changed.

So I suspect you are trying to get Viewchild at the time when it is not filled.

See also:

yurzui
  • 205,937
  • 32
  • 433
  • 399