I have a MapComponent which loads an OpenLayers Map. This component is re-used in various of my Angular app's pages.
The map loads fine the first time. However, when I navigate to another component that contains the map, the map goes blank. In order to see it again, I have to navigate to a component that does not include the map, then navigate back to the desired page.
I only observe this behaviour since upgrading to Angular 10 (from 8).
Openlayers version 6.5 and 5.3 both exhibit this problem.
I've tried forcibly setting this.map = null in an OnDestroy lifecycle hook of my pages. Does not sound like a good solution and does not work.
I've tried throwing an error in AfterContentInit:
ngAfterContentInit() {
throw new Error("gramschaap");
}
It messes a bit with the rendering of the page and of course leaves a big fat error, but works.
ngAfterViewInit:ngAfterViewInit() {
this.initMap();
setTimeout(() => {
if (this.map) {
this.map.setTarget(null);
this.map.setTarget("mapTarget");
}
}, 1000);
}
This of course means the map is blank for a second before it is redrawn; but it works!
ngOnDestroy.ngOnDestroy() {
this.map.setTarget("raargitaar"); // does not exist
}
I thought it may have something to do with the target not initialising a second time. But it does not work.
Another approach could be to use dynamic map ids as a target.
I eliminated my problem similar to your third attempt. However, I gave 0 timeout rather than giving 1 second and you don't need setTarget(null).
private initMap(): void {
this.map = new Map({...})
setTimeout(() => {
this.map.setTarget('id');
}, 0);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With