在我的代码中,我有一个名为 #map 的 div,它将在 for 循环的条件之后显示。
<div *ngFor="let message of fullMessagesArr">
<div *ngIf="message.replyMap">
<div #gmap style="width:100px;height:400px"></div>
</div>
</div>
下面给出了我的 .ts 文件,其中包含 initMap
函数。
@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);
}
initGMap
函数在 sendMessage
函数内被调用。
最佳答案
似乎您正在尝试访问该元素,但该元素对 DOM 不可见,因此您可以执行 setTimeOut 或使用 ngAfterContentInit 生命周期钩子(Hook)来等待 DOM 渲染
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);
}
关于javascript - 使用@viewchild时无法读取 Angular 中未定义的属性 'nativeElement',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57851890/