如何刷新UI而无需在Angular中重新加载页面

时间:2020-06-18 21:46:27

标签: html angular typescript angular-material eventemitter

我的页面中有多个图表,我正在尝试进行删除呼叫,但是由于某些原因,当我单击删除按钮时,图表UI不会立即更新。我总是需要刷新浏览器才能看到更改。

我为她的https://stackblitz.com/edit/angular-ivy-nnun96上传了这两个组件的完整代码,因此,如果我能获得有关如何在用户按下Delete按钮时立即删除UI的任何建议,我将不胜感激。

Mc图表列表TS

  deleteChart(){
    this.chartService.deleteChart(this.chart.guid).subscribe((deleted) => {
      console.log(deleted);
    });
  }

MC图表列表HTML

 <button mat-menu-item (click) = "deleteChart()" *ngIf = "chart.hasAccess && chart.canEdit && !chart.isPublished">Delete Chart</button>

父HTML

       <mc-chart-list [chart]="chart" [editMode]="true" [wsType]="workspace.type"></mc-chart-list>

父母TS

ngOnInit(): void {
this.charts = this.workspace.charts;
}

现在看起来像这样

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用ChangeDetectorRef来检测视图上的更改。

import {ChangeDetectorRef} from '@angular/core';

constructor(private ref: ChangeDetectorRef)

deleteChart(){
    this.chartService.deleteChart(this.chart.guid).subscribe((deleted) => {
      console.log(deleted);
      this.ref.detectChanges();
    });
  }

注意:删除changeDetection:ChangeDetectionStrategy.OnPush(如果正在使用)

答案 1 :(得分:0)

deleteChart(){
    this.chartService.deleteChart(this.chart.guid).subscribe((deleted) => {
      console.log(deleted);
      this.ngOnInit();. // Adding this line should solve
    });
  }