stefan
stefan

Reputation: 3

Angular: Why called google-maps my function in interpolation?

Everytime I hover or interact with the map, my function "getTitle()" is called countless times, but why? I use "@angular/google-maps": "^14.2.2"

map.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.scss']
})
export class MapComponent implements OnInit, OnDestroy {
    private map?: google.maps.Map;
    private center: google.maps.LatLngLiteral;
    private zoom: number;
    
    constructor() {
        this.center = { lat: 47.280622, lng: 8.638879 };
        this.zoom = 15;
    }
    
    ngOnInit(): void {
        this.initializeMap();
    }
    
    initializeMap() {
        this.map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
            center: this.center,
            zoom: this.zoom,
        });
    }
    
    private title: string = "Title";
    private count: number = 0;
    getTitle(): string {
        console.log(this.count, 'DEBUG');
        this.count += 1;
        return this.title;
    }
    
    ngOnDestroy(): void {
    }
}

map.component.html

<div id="map-wrapper">
  <div id="map"></div>
  <div id="list">
    <code>
      {{ getTitle() }}
    </code>
  </div>
</div>

I can't explain how this function is called by Google Maps. I hope someone can help me?

Upvotes: 0

Views: 68

Answers (1)

Schrader
Schrader

Reputation: 490

If you are using functions in your template, angular change detection on default cant "remember" the return and rerun your function on every changedetection run happen in your application.

Calling functions in your template can be have a heavy impact on performance.

So its better to use this.title as a direct binding in your template.

Edit: Something to read about it: https://medium.com/showpad-engineering/why-you-should-never-use-function-calls-in-angular-template-expressions-e1a50f9c0496

Upvotes: 1

Related Questions