cssangulartypescriptleafletngx-leaflet

Hide a leaflet angular map on initial load


i have a map for which following css is used.When the page loads i want the map to be hidden and get loaded only after a button is pressed

From the console i used the following and it was working and it made the map hidden

    document.getElementsByClassName('DemoMap')[0]).style.height="0px";

But from the typescript code

    (<HTMLElement>document.getElementsByClassName('DemoMap')[0]).style.height="0px";

i am getting a runtime error


TypeError: Cannot read property 'style' of undefined

.DemoMap {
  z-index: 1;
  position: absolute;
  width: calc(100% - 600px);
  height: calc(100% - 400px);
  top: 60px;
}

Solution

  • Create a flag isMapVisible = false;

    In your markup use [style.display] to configure the flag's state:

    <div
      style="height: 90vh;"
      [style.display]="isMapVisible ? 'block' : 'none'"
      leaflet
      [leafletOptions]="options"
    ></div>
    
    <button (click)="showMap()">Show map</button>
    

    Use a button to change the boolean's state to true using an event listener:

    showMap() {
        this.isMapVisible = true;
    }
    

    Demo