簡體   English   中英

值更改時,Angular 組件不會更新 UI

[英]Angular component is not updating UI when value changes

我編寫了一個非常簡單的組件,其中包含一個用於跟蹤狀態的變量。 當值改變時,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 的重新繪制。 任何有關如何解決此問題的幫助將不勝感激。

從您的 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>

我現在明白了,將它添加到您的組件中。 工作鏈接

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();
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM