Search code examples
angularangular-ng-if

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> 

When the page opening it's work correctly. When click this button followcontrol() function result will change. My follow() function:

 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.
  }

How can i get the currently value of followcontrol() after follow() function worked?


Solution

  • Save the ids into an array (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;
      });
    }
    

    in your template:

    <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>
    

    So, You'll avoid to use methods inside of your template (which emit side effects), and you have all data prepared from the initialization.