当@input从谷歌地图标记事件更新ngFor不更新 [英] ngFor not updating when @Input updated from google map marker event

查看:151
本文介绍了当@input从谷歌地图标记事件更新ngFor不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立与angular2一个简单的应用程序,我有以下组件:

I'm trying to build a simple app with angular2, I have the below 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);
        }
    }

在我的地图menu.html是:

when my map-menu.html is:

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

和我的应用程序的HTML我有:

and in my app html I have:

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

和列表不会被更新,但是当我加入了注释的setInterval它工作正常。我缺少什么呢?

and the list is not being updated, BUT when I'm adding the commented setInterval it is working fine. what am I missing there?

我创建了一个 plunker 与解决方案

I've created a plunker with the solution

推荐答案

从的用户输入开发指南

角只更新绑定(因此屏幕)如果我们做响应异步事件的东西,如按键。

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

我猜你没有一个异步事件时,标记阵列被更新,所以没有引起角度来运行其变化检测算法。

I'm guessing you don't have an asynchronous event when the markers array is updated, hence nothing is causing Angular to run its change detection algorithm.

更新:的问题是不是说没有一个异步事件,问题是,异步事件( google.maps.Marker.addListener())不受角已知的,因此没有猴子打补丁,因此角不运行它的变化检测算法时的数据的变化。解决的办法是发射区的运行里面的事件()功能:

Update: The issue was not that there wasn't an asynchronous event, the issue was that the asynchronous event (google.maps.Marker.addListener()) is not known by Angular, hence Zone does not monkey patch it, hence Angular doesn't run its change detection algorithm when the data changes. The solution is to emit the event inside Zone's run() function:

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

这将导致角来运行其变化检测算法,注意变化和更新视图。

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

究其原因的setInterval()的工作原理是,因为它是由猴子修补区

The reason setInterval() works is because it is monkey patched by Zone.

请参阅 DiSol的plunker 了解更多详情。
结果如果您想了解更多有关区,观看 MISKO的影片
结果参见 NgZone API文档

See DiSol's plunker for more details.
If you want to learn more about Zone, watch Miško's video.
See also NgZone API doc.

这篇关于当@input从谷歌地图标记事件更新ngFor不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆