[英]How to trigger a function onInit in Angular 9
我有以下 function 當前由單擊按鈕觸發:
export class ExhibitorDetailsComponent implements OnInit {
@ViewChild(MapInfoWindow, { static: false }) infoWindow: MapInfoWindow
openInfo(marker: MapMarker, content) {
this.infoWindow.open(marker)
}
markers = [{
position: {
lat: 52.550267,
lng: 13.4367754,
},
label: {
color: ''
},
title: 'Marker title ',
clickable: true,
options: { },
}]
constructor(
) { }
ngOnInit(): void {
}
}
以及點擊時觸發的視圖:
<google-map>
<map-info-window>{{exhibitor.doc.galleryname}}</map-info-window>
<map-marker #markerElem
*ngFor="let marker of markers"
(mapClick)="openInfo(markerElem)">
</map-marker>
</google-map>
我打算在頁面加載時直接觸發 function,而不需要點擊事件。 來自 AngularJS,我的第一個想法是找到類似於ng-init="openInfo(markerElem)"
東西,但這似乎不適用於現代 angular。
我也嘗試在 ngOnInit function 中添加 function,但它也不起作用。
任何指針?
你必須在 ngAfterViewInt 中響應 Angular 初始化組件的視圖和子視圖方法,因為當你調用 ngOnInit 方法時,視圖還不是渲染器,所以 this.infoWindow 是未定義的。
感謝你的幫助!
這是使它最終起作用的原因:
@ViewChild('markerElem') markerElem;
ngAfterViewInit() {
this.openInfo(this.markerElem, "");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.