我写了一个非常简单的组件,其中包含一个变量来跟踪状态。当值更改时,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的重新绘制。任何有关如何解决此问题的帮助将不胜感激。
答案 0 :(得分:3)
从您的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();
});
}