Fix: Add change detection and prevent duplicate event listeners

This commit is contained in:
2026-02-14 14:59:20 -05:00
parent 0f37c61fae
commit fbfdceeea6
2 changed files with 22 additions and 5 deletions

View File

@@ -8,6 +8,7 @@ import { Component, Output, EventEmitter, AfterViewInit, ElementRef } from '@ang
})
export class MapSvgComponent implements AfterViewInit {
@Output() countryClick = new EventEmitter<string>();
private handlersAttached = false;
constructor(private elementRef: ElementRef) {}
@@ -16,7 +17,9 @@ export class MapSvgComponent implements AfterViewInit {
if (objectElement) {
objectElement.addEventListener('load', () => {
this.attachClickHandlers();
if (!this.handlersAttached) {
this.attachClickHandlers();
}
});
}
}
@@ -39,10 +42,12 @@ export class MapSvgComponent implements AfterViewInit {
path.setAttribute('class', 'country-path');
path.setAttribute('style', 'cursor: pointer;');
path.addEventListener('click', () => {
const clickHandler = () => {
console.log(`Clicked country: ${countryCode}`);
this.countryClick.emit(countryCode.toUpperCase());
});
};
path.addEventListener('click', clickHandler, { once: false });
path.addEventListener('mouseenter', () => {
(path as SVGPathElement).style.fill = '#3498db';
@@ -55,5 +60,8 @@ export class MapSvgComponent implements AfterViewInit {
});
}
});
this.handlersAttached = true;
console.log('Click handlers attached successfully');
}
}

View File

@@ -1,4 +1,4 @@
import { Component } from '@angular/core';
import { Component, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { WorldBankService, CountryData } from '../services/world-bank';
import { MapSvgComponent } from '../map-svg/map-svg';
@@ -14,24 +14,33 @@ export class MapComponent {
loading: boolean = false;
error: string | null = null;
constructor(private worldBankService: WorldBankService) {}
constructor(
private worldBankService: WorldBankService,
private cdr: ChangeDetectorRef
) {}
onCountrySelected(countryCode: string): void {
console.log('Country selected:', countryCode);
console.log('Current state - loading:', this.loading, 'countryData:', this.countryData);
this.loading = true;
this.error = null;
this.countryData = null;
this.cdr.detectChanges();
this.worldBankService.getCountryData(countryCode).subscribe({
next: (data) => {
console.log('Received data:', data);
this.countryData = data;
this.loading = false;
console.log('Updated state - loading:', this.loading, 'countryData:', this.countryData);
this.cdr.detectChanges();
},
error: (err) => {
console.error('API Error:', err);
this.error = 'Failed to load country data';
this.loading = false;
this.cdr.detectChanges();
}
});
}