【问题标题】:Angular: Why called google-maps my function in interpolation?Angular:为什么在插值中调用 google-maps 我的函数?
【发布时间】:2023-01-12 17:43:43
【问题描述】:

每次我悬停或与地图互动时,我的函数“getTitle()”都会被调用无数次,但为什么呢? 我使用 "@angular/google-maps": "^14.2.2"

地图.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 {
    }
}

地图.component.html

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

我无法解释 Google 地图如何调用此函数。我希望有一个人可以帮助我?

【问题讨论】:

    标签: angular typescript google-maps maps


    【解决方案1】:

    如果您在模板中使用函数,默认情况下的角度变化检测无法“记住”返回并在您的应用程序中发生的每次变化检测运行时重新运行您的函数。

    在模板中调用函数可能会对性能产生重大影响。

    因此,最好使用 this.title 作为模板中的直接绑定。

    编辑: 一些关于它的阅读:https://medium.com/showpad-engineering/why-you-should-never-use-function-calls-in-angular-template-expressions-e1a50f9c0496

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多