State and lifecycle of maps in Angular with OpenLayers
The practical decision
Give the map one owner, bridge its events and release owned resources.
A map that works on first load can still fail after navigation, a layer change or a panel resize. These patterns make the integration testable and keep map behaviour connected to the rest of an Angular application.
Create the map in the browser
Give each map instance one owning component. Create it after the DOM target exists using afterNextRender; deferring only setTarget does not make an earlier new Map() safe for server rendering. Give the container a real height and include ol/ol.css.
import {
afterNextRender, ChangeDetectionStrategy, Component,
DestroyRef, ElementRef, inject, viewChild,
} from '@angular/core';
import OlMap from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import OSM from 'ol/source/OSM.js';
import { fromLonLat } from 'ol/proj.js';
@Component({
selector: 'app-map',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<div #target class="map" aria-label="Map" tabindex="0"></div>',
styles: '.map { height: 24rem; }',
})
export class MapComponent {
private readonly target =
viewChild.required<ElementRef<HTMLDivElement>>('target');
private map?: OlMap;
constructor() {
afterNextRender(() => {
this.map = new OlMap({
target: this.target().nativeElement,
layers: [new TileLayer({ source: new OSM() })],
view: new View({ center: fromLonLat([19.94, 50.06]), zoom: 12 }),
});
});
inject(DestroyRef).onDestroy(() => this.map?.dispose());
}
}This minimal example shows initialization and disposal. Child layers can receive a map-host reference through Angular dependency injection. A host reference is not a signal that projection definitions or rendered pixels are ready; wait for the specific operation your task requires. The basic map example shows that composition; the full example collection covers data sources, editing and interactions.
Keep layer order and cleanup explicit
Adding a layer appends it to a collection. Removing and recreating a conditional layer can therefore change the stack. Use declared zIndex values or reconcile the intended order. Test that a selection highlight remains visible after a data layer is toggled.
Removing a layer does not automatically release every associated listener, request or shared source. The code that creates a resource owns its cleanup; shared resources live as long as their consumers need them.
Bridge events once
Translate OpenLayers events into state Angular can observe. A signal read by the template works with zoneless rendering. Pass the owner’s DestroyRef to helpers explicitly when there is no injection context.
import { DestroyRef, signal } from '@angular/core';
import type OlMap from 'ol/Map.js';
export function observeCenter(map: OlMap, owner: DestroyRef) {
const read = () => [...(map.getView().getCenter() ?? [])];
const center = signal(read());
const update = () => center.set(read());
map.on('moveend', update);
owner.onDestroy(() => map.un('moveend', update));
return center.asReadonly();
}Separate commands from observations. “Centre on this record” is a command; “the user panned here” is an observation. Compare values before writing them back so a map event does not trigger an endless navigation loop.
Share IDs and declare projections
Use stable record IDs to connect the map, table and details panel. Feature objects may be replaced during reload. Decide what selection means when a record disappears.
Declare the coordinate system at each data boundary and transform deliberately. A Polish dataset may use EPSG:2180, while a web basemap uses EPSG:3857. Register required projections before use; avoid guessed conversions scattered across components.
Verify navigation, sizing and disposal
Dispose of the map when its owner is finished, unregister owned listeners and cancel owned requests. setTarget(undefined) detaches a retained map; it is a different decision from destroying it.
Test leaving and returning to the screen, changing orientation and opening a panel beside the map. Call updateSize() when a layout change requires it. Use a real browser for sizing and canvas output: jsdom cannot verify rendered map behaviour.
Treat printing as a separate rendering task
Calculate output pixels from paper dimensions and DPI, then derive view resolution for the requested scale. For example, A4 portrait at 150 DPI is about 1240 × 1754 pixels with pixelRatio: 1. Apply the DPI factor once.
const dpi = 150;
const widthPx = Math.round(210 / 25.4 * dpi); // 1240
const heightPx = Math.round(297 / 25.4 * dpi); // 1754Create export layers from shared configuration with separate layer instances. Wait for fonts and rendering, add a timeout, and report failed sources. A completed render cannot prove that an external service returned the intended data. Canvas export also needs compatible CORS responses and the required source attribution.
Connect the boundary to a user task
Clear ownership helps the map keep selection in sync, respond to layout changes and release resources when the user leaves. It also makes failures easier to reproduce.
ClearCraft Geoportal applies these ideas to parcel search, public layers, measurements and the parcel-card export on the web, iPhone, iPad and Android. The examples here explain integration patterns; they are not a complete reproduction of the released application.