Styling and labels · Angular, React and OpenLayers

Hover and selection styles

Combine reactive pointer-hover feature styles and click selection styles on OpenLayers vector polygons in Angular and React without conflicts.

A map of Kraków with four dark red rectangles: the one over Bronowice selected in blue, the one over Podgórze lighter under the pointer.
A screenshot of the example. Map data © OpenStreetMap contributors.

What this example shows

Four dark-red rectangular zones sit across districts of Kraków over OpenStreetMap. Moving the mouse over any rectangle lightens its fill immediately as hover feedback, while clicking selects a rectangle in crisp blue via OpenLayers’ Select interaction.

When you need it

Interactive parcel maps, district pickers and building explorers need distinct visual states for “currently hovered under cursor” versus “actively clicked/selected for inspection”.

Keeping hover state declarative in the template and click selection in aol-interaction-select avoids imperative style mutations that fall out of sync.

The code

The example uses cc-openlayers, my Angular component library for OpenLayers: each aol-… element creates the OpenLayers object it names, updates it from its inputs and disposes of it with the component.

color-select-hover.ts
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import {
  CollectionCoordinatesComponent,
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  FeatureComponent,
  GeometryPolygonComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  SelectInteractionComponent,
  SourceOsmComponent,
  SourceVectorComponent,
  StyleComponent,
  StyleFillComponent,
  StyleStrokeComponent,
  ViewComponent,
} from 'cc-openlayers';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';

/** Polygons that change colour under the pointer and when selected by a click. */
@Component({
  selector: 'app-color-select-hover',
  imports: [
    CollectionCoordinatesComponent,
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    FeatureComponent,
    GeometryPolygonComponent,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    SelectInteractionComponent,
    SourceOsmComponent,
    SourceVectorComponent,
    StyleComponent,
    StyleFillComponent,
    StyleStrokeComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px" (pointerMove)="hover($event)">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-interaction-select [style]="selectedStyle" />
      <aol-view [zoom]="12"><aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" /></aol-view>
      <aol-layer-tile><aol-source-osm /></aol-layer-tile>
      <aol-layer-vector>
        <aol-style>
          <aol-style-stroke color="rgba(90, 17, 26)" [width]="3" />
          <aol-style-fill color="rgba(90, 17, 26, 0.5)" />
        </aol-style>
        <aol-source-vector>
          @for (polygon of polygons; track polygon.id) {
            <aol-feature [id]="polygon.id">
              <aol-geometry-polygon>
                <aol-collection-coordinates [coordinates]="polygon.coordinates" srid="EPSG:4326" />
              </aol-geometry-polygon>
              @if (polygon.id === hovered()) {
                <aol-style>
                  <aol-style-stroke color="white" [width]="3" />
                  <aol-style-fill color="rgba(90, 17, 26, 0.3)" />
                </aol-style>
              }
            </aol-feature>
          }
        </aol-source-vector>
      </aol-layer-vector>
    </aol-map>
  `,
})
export class ColorSelectHover {
  readonly hovered = signal<string | number | undefined>(undefined);
  readonly selectedStyle = new Style({
    fill: new Fill({ color: 'rgba(0, 153, 255, 0.1)' }),
    stroke: new Stroke({ color: 'rgba(0, 153, 255)', width: 3 }),
  });
  readonly polygons = [
    { id: 1, west: 19.86, south: 50.075, east: 19.905, north: 50.095 },
    { id: 2, west: 19.93, south: 50.085, east: 19.975, north: 50.105 },
    { id: 3, west: 19.94, south: 50.025, east: 19.985, north: 50.045 },
    { id: 4, west: 20.01, south: 50.06, east: 20.06, north: 50.085 },
  ].map(({ id, west, south, east, north }) => ({
    id,
    coordinates: [
      [
        [west, south],
        [east, south],
        [east, north],
        [west, north],
        [west, south],
      ],
    ],
  }));

  private readonly map = viewChild.required(MapComponent);
  private readonly layer = viewChild.required(LayerVectorComponent);

  protected hover(event: MapBrowserEvent) {
    const hit = this.map().instance.forEachFeatureAtPixel(event.pixel, (feature) => feature, {
      layerFilter: (layer) => layer === this.layer().instance,
      hitTolerance: 10,
    });
    this.hovered.set(hit?.getId());
  }
}

Architecture and OpenLayers mechanics

On (pointerMove) of aol-map, forEachFeatureAtPixel (scoped strictly to the polygon layer) writes the hovered feature’s ID into a reactive signal. Inside the template, @if attaches a temporary aol-style child only to the matching feature—reverting cleanly to the layer’s base red style as soon as the cursor leaves.

Separately, aol-interaction-select manages clicked selection state and renders the chosen feature with its own dedicated [style].

How it works

  • (pointerMove) on aol-map queries forEachFeatureAtPixel with a layer filter to identify the polygon beneath the cursor.
  • Storing the hovered ID in a signal lets @if mount a highlight aol-style strictly on the hovered feature.
  • Removing the conditional aol-style automatically restores the vector layer’s default dark-red polygon style.
  • aol-interaction-select applies its own blue [style] to whichever polygon the user clicks.

Pitfalls

  • Mutating feature.setStyle(...) imperatively in event handlers conflicts with declarative template bindings—drive conditional aol-style blocks from signals instead.
  • Always pass a layer filter (and optional pixel hit tolerance for thin strokes) to forEachFeatureAtPixel so background vector layers do not steal hover hits.

The same feature in the OpenLayers examples .

Background: state and lifecycle of maps in Angular with OpenLayers, which the components of cc-openlayers take care of.