繁体   English   中英

Angular 2 @ViewChild(“graphCanvas”) graphCanvas:ElementRef 未定义

[英]Angular 2 @ViewChild(“graphCanvas”) graphCanvas: ElementRef is undefined

通过使用 angular 2 构建应用程序,我正面临着 DOM 元素的一个非常奇怪的行为。

我正在使用画布元素在其中绘制图形,并使用@ViewChild 选择元素。 不知何故,angular 表示由于未定义,它无法进一步执行任何方法。

所以我正好在错误发生之前注销。

console.log(this); console.log(this.graphCanvas); 结果: 在此处输入图片说明

希望你明白我的意思。 这包含 graphCanvas 元素,但如果我尝试访问它,我会得到一个未定义的元素。

编辑:我正在使用地图在这张地图上绘制圆圈(数据即项目)。 该问题仅在我启动应用程序时出现,并且仅在我第一次使用搜索时出现。 这两种方法,搜索并点击圆圈,前往相同的方法。

点击圆圈 - 工作: 在此处输入图片说明

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);
});

搜索 - 不工作: 在此处输入图片说明

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);}

在 setGraphView 方法中,未设置元素子级。

console.log只能显示对象的当前状态,而不是调用快照时快照的对象。

它打印对对象的引用,当您在 web devtool 中看到它时,它已更改。

因此,我怀疑您正在尝试在未填充的时候获取 Viewchild。

另见:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM