简体   繁体   English

动态变化 *ngIf State 和 Function Angular

[英]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.当点击这个按钮时followcontrol() function 结果会改变。 My follow() function:我的follow() function:

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

followcontrol() : 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?follow() function 工作后,如何获取followcontrol()的当前值?

Save the ids into an array (ids):将 id 保存到数组 (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.因此,您将避免在模板内部使用方法(这会产生副作用),并且您已准备好初始化中的所有数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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