Javascript 无法读取属性';nativeElement';使用@viewchild时角度中未定义的
在我的代码中,我有一个名为#map的div,它将在for循环的条件之后显示Javascript 无法读取属性';nativeElement';使用@viewchild时角度中未定义的,javascript,angular,typescript,ecmascript-6,single-page-application,Javascript,Angular,Typescript,Ecmascript 6,Single Page Application,在我的代码中,我有一个名为#map的div,它将在for循环的条件之后显示 <div *ngFor="let message of fullMessagesArr"> <div *ngIf="message.replyMap"> <div #gmap style="width:100px;height:400px"></div> </div> </div> initGMap函数在sendMessage函数中被调
<div *ngFor="let message of fullMessagesArr">
<div *ngIf="message.replyMap">
<div #gmap style="width:100px;height:400px"></div>
</div>
</div>
initGMap
函数在sendMessage
函数中被调用。似乎您正在试图访问DOM尚不可见的元素,因此您可以运行setTimeOut或使用ngAfterContentInit生命周期挂钩等待DOM呈现
@ViewChild('gmap') gmapElement: ElementRef;
map: google.maps.Map;
initGMap = () => {
const mapProp = {
center: new google.maps.LatLng(6.9404, 79.8464),
zoom: 15,
mapTypeId: google.maps.MapTypeId.satellite
};
this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
}
export class AppComponent implements OnInit, OnDestroy, AfterContentInit {
public ngAfterContentInit(): void {
const mapProp = {
center: new google.maps.LatLng(6.9404, 79.8464),
zoom: 15,
mapTypeId: google.maps.MapTypeId.satellite
};
this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
}
}
或者使用setTimeOut
initGMap = () => {
const mapProp = {
center: new google.maps.LatLng(6.9404, 79.8464),
zoom: 15,
mapTypeId: google.maps.MapTypeId.satellite
};
setTimeout(() => {
this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
}, 3000);
}
fullMessagesArr
设置在哪里?要么它没有设置,要么它是空的,要么没有任何消息获得replyMap
属性setno,它不是空的,我通过API调用将项放入其中,它不是空的,我检查了是否可以显示该代码?错误不在数组中,当我使用@viewchild并尝试使用initGMap函数加载地图时,会出现问题。这可能是一个同步问题。如果在fullMessagesArr被赋值之前调用initGMap,可能会导致这些问题。顺便说一句,控制台中打印的内容可能会产生误导