使用函数 Angular 动态更改 *ngIf 状态

Dynamic Change *ngIf State with Function Angular

 <ion-col sizeLg="4" size="12" *ngFor="let item of category.menu_items">
   <ion-badge (click)="follow(item)" *ngIf="followcontrol(item.id)">Follow</ion-badge>
 </ion-col> 

当页面打开时它工作正常。单击此按钮时 followcontrol() 函数结果将发生变化。我的 follow() 函数:

 follow(item) {
    
    this.request.postFollowed(item)
    
    this.following(); // This is for succesfull message
  }

followcontrol() :

    followcontrol(id){
    return this.request.getFollowByID(this.followsdata, id) // this function control the data and return a boolean value.
  }

如何在 follow() 函数运行后获取 followcontrol() 的当前值?

将ids存入数组(ids):

ids: number[] = []; 
follows: boolean[] = [];   

ngOnInit() {
  this.your_service.getCategory().subscribe(category => {
    category.menu_items.forEach((item, index) => {
      this.ids[index] = item.id;
      this.followcontrol(item.id, index);
    }
  });    
}

followcontrol(id, index) {
  this.request.getFollowById(this.followsdata, id).subscribe(value => {
    this.follows[index] = value;
  });
}

在您的模板中:

<ion-col sizeLg="4" size="12" *ngFor="let item of category.menu_items; let i = index">
   <ion-badge (click)="follow(item)" *ngIf="follows[i]">Follow</ion-badge>
 </ion-col>

因此,您将避免在模板内部使用方法(会产生副作用),并且您已准备好初始化中的所有数据。