问题
I add to the <ion-content> a ionScroll event which triggers the method foo() and in a <button ion-button> a click event which triggers foo() too. In my template I add for an example {{ x }} and the foo() method increments x.
The button click refreshs the view so that the new value is shown. The scrolling not. If I add a console.log this will print.
If i set the fokus to some element like a textbox or something, the view refreshs and the new value of x shows up.
have someone an idea why?
回答1:
That's because something very interesting and powerfull called Zones. If the concept is new for you, please refer to here and here for a great explanation.
As you can read there,
Application state change is caused by three things:
1) Events - User events like click, change, input, submit, …
2) XMLHttpRequests - E.g. when fetching data from a remote service Timers -
3) setTimeout(),setInterval(), because JavaScript
… it turns out that these are the only cases when Angular is actually interested in updating the view.
That's why the view is not being updated when you scroll, but it does when you touch any of the elements of the page (since it's a user event).
In order to fix this, one of the options is to let Angular know that it needs to be aware of some changes you're just about to make, because things will probably need to be updated. You can do that by running some code (the code that updates the x property) inside a zone, like this:
import { Component, NgZone } from '@angular/core';
@Component({...})
export class MyPage {
constructor(..., private ngZone: NgZone) {}
public yourMethod(): void {
this.ngZone.run(() => {
// Update the x property here, and the view will be updated!
});
}
}
来源:https://stackoverflow.com/questions/42474414/ionic-2-ionscroll-event-to-not-refresh-view