【问题标题】:ExpressionChangedAfterItHasBeenCheckedError when using ReactiveForms and NgbModal使用 ReactiveForms 和 NgbModal 时的 ExpressionChangedAfterItHasBeenCheckedError
【发布时间】:2019-05-14 17:34:04
【问题描述】:

我有一个反应式表单,当用户在输入中按下 ESC 键时,我想在表单隐藏之前显示“你确定”模式。
一旦显示模态,我就会在控制台中收到以下异常:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has 
changed after it was checked. Previous value: 'ng-untouched: true'. Current 
value: 'ng-untouched: false'.

Here is a stackblitz 显示问题(焦点输入并按 ESC)

注意:当您聚焦输入,模糊并再次聚焦时,问题不会显示为ng-untouched 不会再次改变。

有什么解决方法吗?实现此类功能的推荐方法是什么?

提前致谢!

【问题讨论】:

  • 这是因为ng-untouched的值变化非常频繁
  • 在我的情况下 setTimeout 没有解决问题。在打开确认模式之前,我必须将控件设置为已触摸。 control.markAsTouched()

标签: angular angular-reactive-forms ng-bootstrap


【解决方案1】:

我终于找到了解决问题的方法,但仍然保留了脏标志。

当 FormControl 设置为 {updateOn:'change'}(默认值)时,ng-untouched 保持 onBlur。您要做的就是在打开模式之前手动模糊输入。当模态显示时,它无论如何都会模糊。

Here is a stackblitz

【讨论】:

    【解决方案2】:

    试试这个:

    this.form = new FormGroup({
      test: new FormControl('',{updateOn:'submit'})
    })
    

    【讨论】:

    • 它有效,谢谢。以前不知道updateOn。但是:为了实现解释的功能,我只想在表单脏时显示模式。由于 updateOn 设置为 'submit' 只要表单未提交,dirty 就会为 false。
    【解决方案3】:

    另一个技巧是在打开对话框之前blur activeElement。这是一个在选择new 时显示模式对话框的示例。

    {
      type: 'select',
      key: 'destination',
      templateOptions: {
        label: 'To Account',
        options: [...accounts],
        required: true,
        disabled: false,
      },
      hooks: {
        onInit: (field) => {
          field.form.get('destination').valueChanges.subscribe((value) => {
            if( value == 'new' ){
                (document.activeElement as any).blur();
                this.modal.open(AddAccountDialogComponent);
            }
          });
        }
      }
    }
    

    【讨论】:

      【解决方案4】:

      尝试将 onESC 代码块包装在 setTimeout 中,这将使用 zone.js 触发 Angular Change 检测。

      onEsc() {
        setTimeout(()=>{
          const modalRef = this.modalService.open(NgbdModalContent);
          modalRef.componentInstance.name = 'World';
        }, 0);
      }
      

      【讨论】:

        【解决方案5】:

        这不是 keyup 事件的问题,而是您正在使用的自定义模式的问题。尝试删除模态,它会工作,或者你需要先初始化它。

        【讨论】:

          猜你喜欢
          • 2018-01-17
          • 1970-01-01
          • 1970-01-01
          • 2019-03-16
          • 2019-08-01
          • 2017-11-07
          • 1970-01-01
          • 2018-04-12
          • 1970-01-01
          相关资源
          最近更新 更多