barteloma
barteloma

Reputation: 6875

Why angular does not populate view in dynamically created component?

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.

Upvotes: 0

Views: 43

Answers (1)

onik
onik

Reputation: 1631

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)
    }
  }

Upvotes: 2

Related Questions