【问题标题】:Ionic 2 Angular 2 ion-list random shuffle without ngFor没有 ngFor 的 Ionic 2 Angular 2 离子列表随机洗牌
【发布时间】:2016-11-07 21:14:22
【问题描述】:

我有一个这样的列表:

<ion-list>
    <ion-item>item A</ion-item>
    <ion-item>item B</ion-item>
    <ion-item>item C</ion-item>
<ion-list>

如何在渲染前随机洗牌?请注意,我们没有使用 ngFor。

【问题讨论】:

  • 您没有使用 ngFor 有什么原因吗?如果是这样,请添加它。如果您按所示列出项目,它们将始终以相同的顺序呈现。

标签: angular random ionic2 shuffle ngfor


【解决方案1】:

要非常简单地回答,您应该看看那个shuffle technic。这样,您就可以在渲染之前对数组进行随机排序。在您的组件中创建以下函数。

private buildArray(array) {
  return new Promise(resolve => {
    let m = array.length, t, i;

    // While there remain elements to shuffle…
    while (m) {

      // Pick a remaining element…
      i = Math.floor(Math.random() * m--);

      // And swap it with the current element.
      t = array[m];
      array[m] = array[i];
      array[i] = t;
    }

    this.myArray = array;
    resolve(true);
  });
}

然后,在您的构造函数中,您可以执行以下操作:

this.buildArray(this.myArray);

然后渲染它,你有多个选项,你可以使用 *ngFor now 因为你的数组是随机排序的,但是如果出于任何其他原因你更喜欢制作渲染函数,请执行以下操作:

<ion-list id="myArrayList"><ion-list>

制作你的渲染函数:

private renderArray(array, id){
  let item;
  let textItem;
  let i = -1;

  while(array[++i]) {
    item     = document.createElement("ion-item"); // Create item
    textItem = document.createTextNode(array[i].value); // Create item content

    item.appendChild(textItem);
    document.getElementById(id).appendChild(item);
  }
}

最后通过以下方式修改你的构造函数:

this.buildArray(this.myArray).then(() => {
  this.renderArray(this.myArray, "myArrayList");
});

我没有尝试该代码,请告诉我它是否有效,如果您需要更多帮助^_^

【讨论】:

    猜你喜欢
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2013-03-20
    • 2017-04-04
    相关资源
    最近更新 更多