【问题标题】:How to make Ionic 2 Slides component with dynamic number of slides move to some slide right after setting the data?如何在设置数据后立即使具有动态幻灯片数量的 Ionic 2 Slides 组件移动到某个幻灯片?
【发布时间】:2017-10-29 10:43:33
【问题描述】:

我需要使用 *ngFor 从我使用 HTTP 请求获取的数据中动态设置 Ionic 2 Slides 组件的幻灯片,并使其设置为活动的特定幻灯片。

我面临的问题是,在使用数据设置组件的属性时,我仍然无法调用Slides.slideTo(),因为组件尚未更新,我不知道正确的时间去做。我也没有在 Slides 组件上看到可以绑定到的属性,例如 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 处理它?

我正在使用 Ionic 2.2.0 (Angular 2.4.8) 和 Cordova 6.5.0。非常欢迎任何见解。

更新

我发现了一个可能相关的 Ionic 问题:https://github.com/driftyco/ionic/issues/6703

【问题讨论】:

    标签: angular ionic-framework ionic2


    【解决方案1】:

    如果您在 ionViewDidEnter() 内部进行调用,slideTo 函数将按预期工作,例如:

    ionViewDidEnter(){
        this.slides.slideTo(this.index,0);
      }
    

    【讨论】:

      猜你喜欢
      • 2020-08-19
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 1970-01-01
      • 2018-01-12
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多