Why AfterViewInit conference app map

Hi @acarrasco :wave:

I’m copying the code here for reference (please always provide the code or a link to it!):

@Component({
  selector: 'page-map',
  templateUrl: 'map.html',
  styleUrls: ['./map.scss']
})
export class MapPage implements AfterViewInit {
  @ViewChild('mapCanvas') mapElement: ElementRef;

  constructor(public confData: ConferenceData, public platform: Platform) {}

  async ngAfterViewInit() {
    const googleMaps = await getGoogleMaps(
      'AIzaSyB8pf6ZdFQj5qw7rc_HSGrhUwQKfIe9ICw'
    );
    this.confData.getMap().subscribe((mapData: any) => {
      const mapEle = this.mapElement.nativeElement;
      ...
    });
  }
}

The property mapElement contains a reference to the #mapCanvas element in the template:

@ViewChild('mapCanvas') mapElement: ElementRef;

Because the value of mapElement will be undefined until the template has been initialized and added to the DOM, you need to wait until the AfterViewInit lifecycle event to use it, so the code has to go or be called from ngAfterViewInit().

If you try to use mapElement inside ngOnInit(), you will get an error saying that the property nativeElement doesn’t exist on undefined on runtime.

Best,
Rodrigo

1 Like