displaying a grey box on Google Maps using an *ngIf directive

I am working on a component that displays a map.

@Component({
    selector: "panda-map",
    template: `
        <div class="map" [style.height.px]="height">
        </div>
    `
})
export class PandaMapComponent implements OnInit {
    @Input() height: string = "400";
    @Input() scroll: boolean = false;
    map: google.maps.Map;

    constructor(
        private readonly element: ElementRef,
        private readonly logger: NGXLogger) {
    }

    ngOnInit(): void {
        const div = this.element.nativeElement.querySelector("div");
        if (this.map)
            return;

        this.map = new google.maps.Map(
            div,
            {
                zoom: 8,
                center: { lat: -26.1714402, lng: 28.0050053 },
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                scrollwheel: this.scroll
            });
        google.maps.event.trigger(this.map, "resize");
        google.maps.event.addListener(this.map, "idle", function () {
            google.maps.event.trigger(this.map, "resize");
        });
    }
}

To display the map in a parent component, use the following code:

<div class="pull-left shadow-panel map" *ngIf="address">
   <div>
      <panda-map [height]="400">
      </panda-map>
   </div>
</div>

The address on the map is updated periodically.

When the map is created for the first time, it functions correctly. However, if the address is set to null and then changed to a new value, the map only displays a grey box.

Despite trying various ways to refresh the map, none of them have resolved the issue.

View Complete Plunker

Clicking "show/hide" the first time will draw the map, but subsequent clicks result in just a grey box.

Answer №1

The *ngIf directive in Angular will remove the specified tag from your Document Object Model (DOM). However, the ngOnInit function in your component only runs once, causing your map to not be reinitialized correctly.

Instead of using *ngIf, you can achieve the desired result by using the [style.display] property.

<div class="sh" [style.display]="address ? 'none' : 'block'">
    <panda-map></panda-map>
</div>

(I tested this on your plunker and confirmed that it is functioning correctly)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When comparing TypeScript class functions with regular functions and variables, which one yields better performance?

When it comes to defining functions, is it better to use variables or functions directly? Also, how does this affect tree-shaking? I am dealing with a lot of calculation-intensive helper classes and I am unsure about the optimal approach in terms of memor ...

Learn the steps to create a 3D carousel that spins on its own without the need for manual clicks and pauses once the

Looking for a solution to create a 3D carousel that rotates continuously without the need for buttons to be clicked, and pauses when the mouse hovers over it, then resumes rotation when the mouse is not hovering over it. var carousel = $(".carousel"), ...

implementing a like button next to every item on a list using ajax

Help needed: How can I add a like button next to each item on my 'destinations' list? I'm struggling to figure out the placement. Any suggestions? Below is the content of my dashboard.html.erb file: <div class="destination-list"> ...

Having trouble with nested requests and appending using Jquery or JavaScript?

Greetings everyone, I want to apologize in advance for any spelling errors or mistakes in my message. I struggle with dyslexia and other learning difficulties, so please bear with me. I am using this time during lockdown to learn something new. This is my ...

Deleting an item in Vue.js with the removal feature

After deleting items from my list, they remain visible until I manually refresh the page. How can I fix this issue? List <tbody> <tr v-for="school in schools" v-bind:key="school.id"> <td>{{ school.id }}</td> &l ...

Is it necessary to perform a specific action if the text within a div matches pre

I've been struggling to make this work properly. Even after removing the AJAX POST function, the issue persists. No alerts or any indication of what's going wrong. Check out the code on JSFiddle: HTML <div class="notification"> ...

How can I achieve a smooth opacity transition without using jQuery?

Although I understand that JQuery offers functions for this purpose, I am interested in finding a solution using only pure javascript. Is there a way to change the CSS opacity setting over time? Perhaps utilizing a unix time stamp with millisecond precisi ...

Attempting to transmit checkbox data in jade

I am currently developing an app with Express, Node.js, and Mongo. I have encountered an issue while passing checkbox values to my database. My goal is to only pass the values of checked checkboxes back to the database. In my index.jade file, I attempted ...

I am facing an issue with Angular 14 and Webpack 5, where certain unnecessary nodejs modules seem to be hindering me from successfully serving

I have recently started working on a cutting-edge Angular 14 application. My current node version is v14.20.0, and npm version is 8.17.0. Despite my best efforts, I seem to be facing an issue with multiple nodejs dependencies being included in my project ...

Navigating React: Learn the ins and outs of accessing and modifying state/attributes from a different component

Looking to update the attribute values of ComponentB from ComponentA (currently using an index). I attempted to call lower component functions to modify their state/values. import React from 'react' class TaskComp extends React.Component{ ...

I encountered an issue trying to locate the module '@angular/compiler-cli'

I've encountered an issue with my new project as it's not allowing me to run 'ng serve' due to the 'cannot find module @angular/compiler-cli' error. Despite trying to clear the cache and deleting the node_modules folder withi ...

Is it possible to conceal the mapbox access token during the map initialization process?

I have successfully integrated the mapbox API to create an interactive map on my website. To ensure the security of my access token, I have set up a proxy to handle the API requests externally. However, I am facing a challenge when it comes to hiding the a ...

I am currently exploring React Router, but I am struggling to grasp this particular behavior

My Express server serves the Create-React-App build. When I access http://localhost:8000/ while the server is listening, my page loads correctly. However, if I reload the page or navigate directly to it from the navigation bar, instead of seeing the UI, pl ...

Ways to resolve the error "Uncaught TypeError: data.map is not a function"

Currently developing an app using reactJS and encountering the following error in the console when using the map function: TypeError: data.map is not a function. Despite successful API data calling as confirmed by console.log, the error persists when tryin ...

When adding additional items in Angular's mat-select with multiselect, previously selected options will be reset

I am encountering an issue with a mat-select in my Angular application that has multiselect enabled. Within the mat-select, there is an input used for filtering available options. The problem arises when I select some options, filter using the search inp ...

Exploring Zustand through Laravel validation errorsUnderstanding Zustand can be

I'm currently working on incorporating Zustand into my NextJS application. I have set up a Laravel endpoint for user login functionality. When there are validation errors, the endpoint sends back JSON in the following format: { "message" ...

Issues with loading JSON data through JQuery

I am completely new to the process of loading JSON text using JavaScript or JQuery. JSON is a new concept for me as well. Currently, I have PHP providing me with some JSON text containing images stored on my server in the following format: [ [{ ...

Generate an instance containing attributes that correspond to constant string values within a class

In the world of TypeScript, I have a scenario that might be a bit tricky, but I'll throw it out there anyway. Let's say I start with a base service class: export default class Service { public static readonly accessorName: string constructo ...

Angular2 allows for the firing of all columns in one click using *ngFor

<tr *ngFor = 'let student of students> <td contenteditable="true" class ='phone' #button> {{student.phone}} <i (click)='showbox()' class = ' glyphicon glyphicon-edit'></i> <input *ngIf=&apo ...

Creating a collapsing drop down menu with CSS

I utilized a code snippet that I found on the following website: Modifications were made to the code as shown below: <div class="col-md-12"> ... </div> However, after rearranging the form tag, the drop-down menu collapse ...