首页 > 解决方案 > ngIF 在 Ionic4 中一直循环

问题描述

我正在开发一个具有聊天组功能的聊天应用程序。我创建了“创建新组”和“编辑现有组”页面。在我的“编辑组”页面中,我正在加载所有用户列表并检查成员是否已经存在于组中,以便提供添加或删除现有成员以及新成员的功能。我的代码是这样的:

编辑-group.page.html

//Here I have around 150 friends/total users
<ion-item *ngFor="let friend of friends | friendFilter: searchFriend">
    <ion-avatar slot="start">
        <img src="{{ friend.photoURL }}" onError="this.src='./assets/img/default-dp.png'"/>
    </ion-avatar>
    <ion-label>
        <h2>{{ friend.fullName }}</h2>
        <p class="emailCustom">{{ friend.email }}</p>
    </ion-label>

//****This is where I am facing problem. 
//**** This buttons are add or remove members. Notice here my *ngIF statement! 

    <ion-button fill="clear" slot="end" color = "light" (click)="addToGroup(friend); $event.stopPropagation()" *ngIf="!inGroup(friend) && checkadmin()">
        <ion-icon slot="icon-only" name="add"></ion-icon>
    </ion-button>
    <ion-button fill="clear" slot="end" color = "light" (click)="removeFromGroup(friend); $event.stopPropagation()" *ngIf="inGroup(friend) && checkadmin()">
        <ion-icon slot="icon-only" name="close"></ion-icon>
    </ion-button>
</ion-item>

注意*ngIf离子按钮中的状态。

*ngIf通过函数检查朋友是否已经是组的成员,inGroup()并且它还使用checkadmin()函数检查朋友在哪里是管理员。

我的功能如下:

编辑-group.page.ts

inGroup(friend) {
    //Currently this.groupMembers.lenth is 3 but this function is called 150 times as I have 150 users
    for (var i = 0; i < this.groupMembers.length; i++) {  
      console.log("Kartik In Group Count: " + i);
      if (this.groupMembers[i].$key == friend.$key) {
        return true;
      }
    }
    return false;
  }

  checkadmin() {
    if (this.group.admin == this.afAuth.auth.currentUser.uid) {
      return true;
    } else {
      return false;
    }
  }

所以正在发生的是,我总共有 150 个用户*ngFor="let friend of friends"在 html 中的 ion-item 中循环。inGroup(friend)并为每个朋友checkadmin()检查功能。

现在,一旦页面加载,我的应用程序就会永远进入循环。inGroup()andcheckAdmin()函数不断*ngIf循环。知道我在这里做错了什么吗????

标签: angularloopsionic-frameworkangular-ng-if

解决方案


假设您在浏览器中没有任何控制台错误并且您有可用的数据,我真的不能说出了什么问题。

但我会使用*ngIf else来呈现 HTML 并更新我的代码,如下所示:

 <ion-button fill="clear" slot="end" color = "light" (click)="removeFromGroup(friend); $event.stopPropagation()" *ngIf="inGroup(friend) && checkadmin(); else notInGroup">
        <ion-icon slot="icon-only" name="close"></ion-icon>
    </ion-button>

<ng-template #notInGroup
<ion-button fill="clear" slot="end" color = "light" (click)="addToGroup(friend); $event.stopPropagation()">
            <ion-icon slot="icon-only" name="add"></ion-icon>
        </ion-button>
</ng-template>

还使用 lodash 函数或java 脚本inGroup(friend)将您的更新为这样的:some

inGroup(friend) {
    return _.some(this.groupMembers, (member) => member.$key === friend.$key);
}

并且 checkadmin 可以是 OnInit 中的布尔集并用于*ngIf

boolean isAdmin  = (this.group.admin === this.afAuth.auth.currentUser.uid)

推荐阅读