I am running Angular 6 and I want to dynamically add a layer to a leaflet map, but I can't detect changes in leafletLayers if the layers are modified from another component. Everything works fine if the layer changes are performed from map.component
but it doesn't work if I make changes from outside:
Example:
map.component.ts
layers: Layer[];
addPolygon () {
this.layers = [polygon([[ 43, 3 ], [ 42, 0 ], [ 44, 1 ]])]
}
map.component.html
<div class="map"
leaflet
(leafletMapReady)="onMapReady($event)"
[leafletOptions]="options"
[leafletLayers]="layers">
</div>
<div>
<button type="button" name="button" (click)="addPolygon()"></button>
</div>
Everything works fine now, the polygon shows up as soon as I click the button. But I need that button to be in another component (form.component.ts
), so I tried sharing the addPolygon()
function with a service:
server.service.ts
@Injectable()
export class ServerService {
addPolygon: Function;
}
I modified MapComponent
and added the costructor for calling the service
map.component.ts
export class MapComponent{
layers: Layer[];
constructor(private serverService: ServerService){
this.serverService.addPolygon = this.addPolygon
};
form.component.ts
export class FormComponent implements OnInit {
constructor(private serverService: ServerService) { }
triggerMap() {
this.serverService.addPolygon()
}
}
But If I bind triggerMap()
on a button in form.component.html
the polygon does not get added to the map. The console however says that addPolygon
in map.component.ts
is reached.
I tried even using NgZone
, but it does not make any difference. Any suggestion?
Angular CLI: 6.0.8