Angular 2.0 (Beta, ES5) UI not updating via custom event

狂风中的少年 提交于 2019-12-13 19:48:39

问题


I am having an issues with Angular 2.0.0-beta.2

I have two components loaded separately into a page and communicate is performed between the Angular 2 components and the 'container' website, these events are performed via jQuery's .trigger() and .on().

The idea of this is these components can be integrated into an external website and a predefined set of events can be used to interact between one another.

The issue I am having with angular2 however is that the binding is not updating the UI immediately if a change is made as the result of an event, see the Plunkr here: https://plnkr.co/edit/VReV7dpx2dYjtDSg9iA4?p=preview

<button (click)="toggle()">Click Me to Toggle</button>

If you click 'Click me to Toggle', this updates the internal 'initialHide' and shows the hidden div instantly. If you click 'Click me for ShowHide' it fires an event from ComponentOne, which is picked up by ComponentTwo. It updates 'initialHide' but does not update the UI instantly. If you then click 'Click me for Event' it then picks up that an internal property has changed and updates the UI.

So, my question is - why is this? Is it the context in which the 'initialHide' property is being updated? I first thought it may be an error in the event, but you can see from the console logs that the event is firing just fine and updating the initialHide property, the UI does not pick up the binding however.

Is there a way I can force this? Or a mechanism I can use that will update the bindings automatically when invoked via an event from an external source.


回答1:


Resolved by injecting NgZone into the constructor. I then execute the event code in zone.run()

https://plnkr.co/edit/VReV7dpx2dYjtDSg9iA4?p=preview

constructor : [ng.core.NgZone, function (zone) { ... }
this.updateComp = function() { zone.run() { ... } );



回答2:


If you don't use on() but instead Angulars mechanisms to register event handlers than you don't have issues with code running outside Angulars zone and updating model values not initiating a change detection cycle.

You can use

ng.core
  .Component({ 
      ..., 
      host: {'(window:some-event)':'someFunction($event)'},
  }) 

and when someFunction() is called and it udates model values, Angulars change detection will recognize it.




回答3:


I ran into the same problem (though in an Ajax callback). I updated zone.js to the latest from https://github.com/angular/zone.js/tree/master/dist and it works now.



来源:https://stackoverflow.com/questions/35287164/angular-2-0-beta-es5-ui-not-updating-via-custom-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!