【问题标题】:Expression Changed after it has been checked Angular表达式在检查后更改 Angular
【发布时间】:2020-05-29 14:32:45
【问题描述】:

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

这是我的代码:

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


我有这个错误:

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

你能帮帮我吗?非常感谢!

【问题讨论】:

  • 你在哪里设置 documentLink?
  • 我的 ts 中有这样的东西:@ViewChild('documentLink', {static: false}) inputDocumentLink : ElementRef;
  • 我在我的方法中采用这样的值: const link = this.inputDocumentLink.nativeElement.value;
  • 可以把你的ts文件放在上面吗?
  • @Aakash Garg - 据我所知,#documentLink 已在模板中设置。

标签: angular error-handling upload checked


【解决方案1】:

问题在于使用异步管道并在模板中引用该值。

从模板中移除异步管道

在 Ts 里有它的样子

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 serve angular 中,每次更改检测都会两次,以让您知道代码中的不规则性。尝试运行 ng serve --prod 你不会得到这个错误。但是你应该采用我给出的方法,因为这个错误是为了避免这种违规行为。

【讨论】:

    【解决方案2】:

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

    下面的代码展示了如何继续使用async 管道而不重复它。异步结果存储在包含ng-container*ngIf 条件中设置的doc 对象中(创建对象可确保条件始终为true)。然后我们使用doc.url 作为inputdiv 元素的*ngIf 条件中的值。

    <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 以获取演示。

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 2016-10-19
      • 2017-05-08
      • 1970-01-01
      • 1970-01-01
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 2018-12-19
      相关资源
      最近更新 更多