'OpenLayers dynamically add an Attribution

I have an OpenLayers map that is instantiated at the start of the application with an empty control array, and would like to add an Attribution at a later stage when a Bing Map is loaded (we have a number of maps, but the attribution is to be shown only here, hence the need for the dynamic inclusion). I have been following the OL example here: https://openlayers.org/en/latest/examples/attributions.html

How would I go about doing this dynamically? This is what I have been battling for quite some time, but had no luck so far with any variation on:

     this.map.addControl(defaultControls({attribution: 
    false}).extend([attribution]).get('Attribution'));

I assume the issue lies with the getter. It takes a string, but it isn't clear to me what I need to ask for. Or perhaps I need to call something else? I am bit stumped with this one.



Solution 1:[1]

import Attribution from 'ol/control/Attribution';
import Map from 'ol/Map';
import OSM from 'ol/source/OSM';
import TileLayer from 'ol/layer/Tile';
import View from 'ol/View';
import {defaults as defaultControls} from 'ol/control.js';

const map = new Map({
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 5,
  }),
  layers: [
    new TileLayer({
      source: new OSM(),
    }),
  ],
  controls: defaultControls({attribution: false}),
  // or
  // controls: [],
});
const attributions = new Attribution();
setTimeout(function () {
  map.addControl(attributions);
}, 6000);

// to remove it
// this.map.removeControl(attributions);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MoonE