简体   繁体   中英

Update component after variable change

I need to update an HTML table after updating my values. On Ionic (based on Angular) all was working fine when I was calling my datas loading function. But in Angular, whenever I call my data loading function, the array isn't updated..

I've already tried to deal with ChangeDetectorRef but nothing works...

Here are my functions :

loadCat() {
    this.apiService.listCat().then(data => {
      this.categories = data;
    });
    this.ref.detectChanges();
  }

  addCat() {
    this.apiService.createAssoc(this.label);
    this.assoForm.reset();
    this.loadAssoc();
  }

  deleteCat(id) {
    this.apiService.deleteCat(id);
    this.notify.fireSuccess("La catégorie a bien été supprimée !", "Bye bye !");
    this.loadCat();
  }

And here is a part of HTML table code :

 <tbody>
                        <tr *ngFor="let cat of categories; index as i">
                            <th scope="row">{{ i+1 }}</th>
                            <td>{{ cat.label }}</td>
                            <td><button (click)="deleteCat(cat._id)" class="btn btn-danger">Supprimer</button></td>
                        </tr>
                    </tbody>

I need by tags to be reload with my new categories values but nothing works...

您必须使用this.ref.markForCheck();

No point in calling change detection actually before receiving data. You should move change detection to then block because it's called asynchronously after loadAssoc has been called.

Sometimes change detection should be wrapped with setTimeout because variable perhaps hasn't been updated in time. Set timeout will trigger change detection after call stack has been cleared which will guarantee that variable had been updated.

loadAssoc() {
    this.apiService.listAssoc().then(data => {
      this.assoc = data;
      setTimeout(() => this.ref.detectChanges());
    });
  }

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