我需要使用 *ngFor
从我使用 HTTP 请求获得的数据中动态设置 Ionic 2 幻灯片组件的幻灯片,并将其设置为特定幻灯片设置为活动状态。
面临的问题是,在使用数据在组件上设置属性时,我仍然无法调用Slides.slideTo()
,因为组件尚未更新,并且我不知道执行此操作的正确时间。我也没有看到可以绑定到的幻灯片组件上的activeSlide
等属性。
以下是描述我尝试过的代码:
<ion-slides>
<ion-slide *ngFor="let obj of myObjects">
<div>{{ obj.title }}</div>
</ion-slide>
</ion-slides>
this.http.get('http://example.com', options)
.toPromise()
.then(response => {
this.myObjects = response.json() as MyObject[];
this.currentObject = this.myObjects.find(obj => obj.is_selected);
// Get the index of the slide I want to set as active.
let index = this.myObjects.indexOf(this.currentObject);
// Set it as active -- doesn't work here, because this.slides isn't updated yet.
this.slides.slideTo(index, 0);
// I tried using ChangeDetectorRef.detectChanges() and looked at
// the length of slides, but it seems that it doesn't run change
// detection immediately.
//
// this.ref.detectChanges();
// console.log(this.slides.length()) // returns 0
// Calling Slides.update() after the detectChanges() doesn't help.
//
// this.slides.update();
// console.log(this.slides.length()) // still 0
// I tried setTimeout(callback, 0) to run this after the stack is empty
// and presumably the change detection has run, but still no dice.
//
// setTimeout(() => {
// console.log(this.slides.length());
// }, 0); // doesn't work
// What is interesting, but also a bit disturbing, is that setting
// the timeout to some other value sometimes returns a value
// indicating that a change detection has run and sometimes it's
// still 0. The longer the timeout, the more probable it runs after
// the change detection, but I noticed that up to 20ms I never got
// anything else than 0, but at 25ms I tend to get proper values
// (but not always). I'm running this on Android device with
// Visual Studio Code's default configuration "Run Android on device".
//
// setTimeout(() => {
// console.log(this.slides.length());
// }, 25); // sometimes works
})
对于 Vue 框架,我曾经在这种情况下使用 Vue.nextTick()
,但由于setTimeout(callback, 0)
似乎不起作用,我应该如何使用 Angular 2 来处理它?
(Angular 2.4.8(和Cordova 6.5.0。任何见解都将非常受欢迎。
更新
我发现了一个可能相关的离子问题:https://github.com/driftyco/ionic/issues/6703
如果您在ionViewDidEnter((中进行调用,slideTo函数将按预期工作,例如:
ionViewDidEnter(){
this.slides.slideTo(this.index,0);
}