表达式在检查角度后已更改

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

我具有用于上传文档的输入,并且我正在尝试检查它是否为空以显示警报。

这是我的代码:

<div class="form-group">
    <input type="file" name="file" accept="application/pdf, application/msword, application/vnd.ms-powerpoint" 
    (change)="onUpload($event)">
    <input type="text" #documentLink class="form-control" name="urlDocument" [value]="urlDocument | async">
</div>
<div *ngIf="!documentLink.value" class="alert alert-danger">
   Imaginea de coperta este necesara!
</div>


enter image description here

我有此错误:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
Previous value: 'ngIf: true'. Current value: 'ngIf: false'.

我使用此Viewchild获取值

@ViewChild('documentLink', {static: false}) inputDocumentLink : ElementRef;

这就是我将其添加到数据库中的方法:

const link = this.inputDocumentLink.nativeElement.value;
...

您能帮我吗?非常感谢!

angular error-handling upload checked
2个回答
2
投票

问题是使用异步管道并在下面的模板中引用该值。

从模板中删除异步管道

在T中有它的样子

public inputValue;
ngOnInit() {
    this.getData();
}

public getData() {
   this.urlDocument.subscribe((res) => {
          this.inputValue = res;
   });
 } 

HTML:-

<div class="form-group">
    <input type="file" name="file" accept="application/pdf, application/msword, application/vnd.ms-powerpoint" 
    (change)="onUpload($event)">
    <input type="text" #documentLink class="form-control" name="urlDocument" [value]="inputValue">
</div>
<div *ngIf="!inputValue" class="alert alert-danger">
   Imaginea de coperta este necesara!
</div>

原因:-在浏览模板时未定义url文档,当它的另一个生命周期挂钩重新检查模板时,由于可观察到的发射值而对其进行了更改。因为在正常的ng服务角度中,每次更改检测都会执行两次,以使您知道代码中的不规则性。尝试运行ng serve --prod,您将不会收到此错误。但是您应该采用我给出的方法,因为这样做会避免出现此类错误。


0
投票

问题是您的*ngIf条件取决于使用数据绑定更新的输入元素的属性。为了避免异常,您应该引用原始数据而不是element属性。

以下代码显示了如何不重复使用async管道。异步结果存储在以doc*ngIf条件(该条件始终为ng-container)设置的true对象中。然后,我们将doc.url用作input元素的*ngIfdiv条件中的值。

<ng-container *ngIf="{ url: urlDocument | async } as doc">
  <div class="form-group">
    ...
    <input type="text" #documentLink [value]="doc.url" ...>
  </div>
  <div *ngIf="!doc.url" ...>
     Imaginea de coperta este necesara!
  </div>
</ng-container>

请参见this stackblitz以获取演示。

© www.soinside.com 2019 - 2024. All rights reserved.