<...">

Google maps gray box on * ngIf

I have a component.

@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"); }); } } 

The map is displayed on the parent component as follows:

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

The address changes periodically.

When creating a map for the first time, it works perfectly. If the address is set to null and then a new value is assigned to the address, only a gray square is displayed on the map.

As you can see, I tried various update mechanisms, none of which seem to update the map correctly.

Complete plunker

When you press the show / hide button, the map is drawn. After that, it's just a gray box.

+1
javascript angular google-maps typescript
source share
1 answer

The angular * ngIf directive removes a tag in your DOM. But your component executes ngOnInit only once. Thus, your card is not being restored correctly.

Instead of * ngIf

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

(I tried on your plunker and it works correctly)

0
source share

All Articles