如何在Angular 9中触发onInit函数

我现在通过单击按钮触发以下功能:

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>

I intend to trigger the function directly on page load, without needing the click event. Coming from AngularJS, my first idea was to find something similar to ng-init="openInfo(markerElem)", but that doesn't seem to work in modern angular.

我也尝试过在ngOnInit函数中添加该函数,但是它也不起作用。

有指针吗?

评论
  • Zero
    Zero 回复

    感谢你的帮助!

    这是最终使它起作用的原因:

    @ViewChild('markerElem') markerElem;
    
    ngAfterViewInit() { 
    
        this.openInfo(this.markerElem, "");
    
    }
    
  • out
    out 回复

    您必须在ngAfterViewInt中执行此操作,以便在Angular初始化组件的视图和子视图方法后做出响应,因为调用ngOnInit方法时该视图尚未渲染,因此this.infoWindow是未定义的。