Angular 2:生成随机int抛出错误

时间:2017-04-27 15:09:16

标签: angular random

我有一个列表,我使用随机数来选择一个头像并抛出以下错误:

HelloIonicPage.html:33 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

查看:

  <ion-list>
    <ion-item *ngFor="let client of clients; let i = index;>
      <ion-avatar item-left>
        <img [src]="getRandomInt(0, 9)">
      </ion-avatar>
    </ion-item>
  </ion-list>

.TS

getRandomInt(min, max) {
    let num =  Math.floor(Math.random() * (max - min + 1)) + min;
    return "https://randomuser.me/api/portraits/lego/" + num + ".jpg"
}

1 个答案:

答案 0 :(得分:0)

我猜你可以尝试使用background-image[ngStyle]

进行欺骗

HTML

<ion-list>
  <ion-item *ngFor="let client of clients; let i = index; let r = getRa" >
    <ion-avatar item-left>
     <div class="avatar-photo" [ngStyle]="{ 'background-image': 'url(' + getRandomInt(0, 9) + ')' }"></div>
    </ion-avatar>
  </ion-item>
</ion-list>

您还需要其他CSS,因此可以自定义,随需更改

.avatar-photo {
    width: 160px;
    height: 160px;
    border-radius: 50%;
    background-size: contain;
    background-repeat: no-repeat;
}

我希望它有所帮助!