[值更改时,Angular组件不更新UI

问题描述 投票:2回答:1

我已经编写了一个非常简单的组件,其中包括一个用于跟踪状态的变量。当值更改时,UI应该相应地显示不同的内容。为了测试功能,我创建了组件,并使用等待功能在5秒钟后更新值。当变量被更改时(我通过将更改记录到控制台来验证了更改),它似乎并未触发UI刷新。我有一个预感,我需要使该变量可观察,但是我不确定这是否太过严格,是否有更简单的解决方案。这是我组件的代码

import { Component, OnInit } from '@angular/core';
import { MatSnackBar } from '@angular/material';

@Component({
  selector: 'app-export',
  templateUrl: './export.component.html',
  styleUrls: ['./export.component.scss']
})
export class ExportComponent implements OnInit {

  flowId: number;

  constructor(public snackBar: MatSnackBar) {
    this.flowId = 1;
  }

  ngOnInit() {}

  incrementFlowID() {
    this.flowId++;
    console.log(this.flowId);
  }

  openSnackBar(message: string, action: string) {
    const snackBarRef = this.snackBar.open(message, action, {duration: 5000, });
    snackBarRef.afterDismissed().subscribe(() => {
      this.incrementFlowID();
    });
  }

  initiateExport() {
    this.incrementFlowID();
    this.openSnackBar('Your pdf document is being generated', '');
  }

}

这里相关的相应HTML代码段看起来如下:

    <div *ngIf="this.flowId == 1">
      <button mat-raised-button (click)="initiateExport()">Create PDF</button>
    </div>
    <div *ngIf="this.flowId == 2">
      <b>Your pdf document is being created.</b>
    </div>
    <div *ngIf="this.flowId == 3">
      <b>PDF document is complete.</b> <br/>
      <a href="#">Download document</a><br/>
    </div>

似乎“ afterDismissed”事件正确更新了ID号,但变量的更改不会触发UI的重新绘制。任何有关如何解决此问题的帮助将不胜感激。

angular typescript
1个回答
1
投票

从您的html中删除'this'

<div *ngIf="flowId == 1">
  <button mat-raised-button (click)="initiateExport()">Create PDF</button>
</div>
<div *ngIf="flowId == 2">
  <b>Your pdf document is being created.</b>
</div>
<div *ngIf="flowId == 3">
  <b>PDF document is complete.</b> <br/>
  <a href="#">Download document</a><br/>
</div>

我现在看到的,将其添加到您的组件中。 Working Link

import {Component, ViewEncapsulation, ChangeDetectorRef} from '@angular/core';

...
constructor(
public snackBar: MatSnackBar,
private ref: ChangeDetectorRef
) {
  this.flowId = 1;
}

...

openSnackBar(message: string, action: string) {
  const snackBarRef = this.snackBar.open(message, action, {duration: 5000, });
  snackBarRef.afterDismissed().subscribe(() => {
    this.incrementFlowID();
    this.ref.detectChanges();
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.