gpt4 book ai didi

当值发生变化时,Angular 组件不会更新 UI

转载 作者:行者123 更新时间:2023-12-02 11:18:10 25 4
gpt4 key购买 nike

我编写了一个非常简单的组件,其中包含一个用于跟踪状态的变量。当值发生变化时,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 的重新绘制。任何有关如何解决此问题的帮助将不胜感激。

最佳答案

Remove 'this' from your html

<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>

I see now, add this to your component. 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();
});
}

关于当值发生变化时,Angular 组件不会更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59686458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com