0

I have a component that using third party map library. MousePositionComponent is in my MapModule.

@Component({
  ....,
  template: `<span>{{coordinate}}</span>`
})
export class MousePositionComponent implements OnInit {

  public coordinate: string;

  ngOnInit() {
    this.map.on("click", this.onMapClicked());
  }

  private onMapClicked(): (evt: MapBrowserEvent) => void {
    return (event: MapBrowserEvent) => {
      let coordinate = this.transformCoordinate(event.coordinate);
      this.coordinate = this.formatCoordinate(coordinate);
      console.log(this.coordinate)
    }
  }
}

So I am using MapModule in my ApplicationModule. If I use in a dynamically created SommeComponent, it works. If I have AnotherComponent that dynamically created, the view does not update, but console.log(this.coordinate) works.

1 Answer 1

2

the function executes outside Angular's zone, so you need to tell it explicitly, to run change detection on click event

constructor(private ngZone:NgZone){

}



 ngOnInit() {
    this.map.on("click", this.ngZone.run(()=>this.onMapClicked()));
  }

  private onMapClicked(): (evt: MapBrowserEvent) => void {
    return (event: MapBrowserEvent) => {
      let coordinate = this.transformCoordinate(event.coordinate);
      this.coordinate = this.formatCoordinate(coordinate);
      console.log(this.coordinate)
    }
  }
Sign up to request clarification or add additional context in comments.

3 Comments

How to remove event ngOnDestroy?
reference this callback somewhere in components field and on ngOnDestroy call thiss.map.removeEventListener("click",callbackReference)
But we put this.ngZone.run() function in this.map.on method. So I think use for removing like this.mapComponent.map.un("click", this.ngZone.run(() => this.onMapClicked())); is it true?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.