NgTo update when updating @Input from google map marker event

I am trying to create a simple application with angular2, I have the following component:

@Component({ selector: 'map-menu', templateUrl: './angular-app/components/map-menu.html' }) export class MapMenuComponent { @Input() selectedMarkers: Array<google.maps.Marker>; constructor() { // setInterval(() => { // console.log(this); // }, 1000); } } 

when my map-menu.html:

 <ul class="nav nav-sidebar"> <li *ngFor="#marker of selectedMarkers #i = index"><a href="#">{{marker.data.name}}</a></li> </ul> 

and in my html application I have:

 <map-menu [selectedMarkers]="selectedMarkers"></map-menu> 

and the list is not updated, BUT, when I add a commented-in setInterval, it works fine. What am I missing there?

I created plunker using solution

+1
angular google-maps google-maps-api-3 angular2-template angular2-directives
source share
1 answer

In the user manual for data entry :

Angular updates the bindings (and therefore the screen) if we do something in response to asynchronous events, such as keystrokes.

I assume that you do not have an asynchronous event when updating the marker array, so nothing leads Angular to run the change detection algorithm.

Update: The problem is not that there was no asynchronous event, the problem was that the asynchronous event ( google.maps.Marker.addListener() ) is not known to Angular, therefore Zone is not a monkey pathet, so Angular does not start the change detection algorithm when data change. The solution is to emit an event inside the Zone run() function:

 marker.addListener('click', () => { this.zone.run(() => { this.markerClickEvent.next({data:{name: 'another'}}); }); }); 

This will cause Angular to run the change detection algorithm, notice the change, and update the view.

The reason for setInterval() is that it is beheaded by the zone.

See DiSol plunker for details .
If you want to know more about the zone, watch the Miลกko video .
See also NgZone API doc .

+4
source share

All Articles