简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM