2017-08-24 24 views
0

当使用输入文本中的(keyup.enter)显示模式时,使用带有角度4和引导程序4(v4.alpha,ng-bootstrap)的可视代码来抛出Error:ExpressionChangedAfterItHasBeenCheckedError

当你完成键入一些数字并按下输入而不失去焦点(显示模式)时显示问题,显示模式,但在控制台显示错误提到。 (错误:ExpressionChangedAfterItHasBeenCheckedError),并指出错误来自于输入文本:

<div class="form-group" 
     [ngClass]="{'has-error': (numeroDocuVar.touched 
     ||numeroDocuVar.dirty) && !numeroDocuVar.valid }"> 
     <div class="form-group"> 
      <div class="input-group"> 
       <input class="form-control" id="numeroDocuId" 
         type="text" placeholder="Numero documento (requerido)" 
         [(ngModel)]="IdNumeroDocu" name="numeroDocu"                 
         #numeroDocuVar="ngModel" 
        (keyup.enter)="onSearchDocumento(numeroDocuVar.value)" 
         required /> 
       <span class="input-group-addon fa fa-search" 
         (click)="onSearchDocumento(numeroDocuVar.value)" 
         style="cursor:pointer"> 
       </span> 
      </div> 
    </div> 
</div> 

我已阅读,我可以用ngAfterContentInit做到这一点,但这个变量没有被计算填补,这是谁填补了用户输入文本中的信息。

我使用ng-bootstrap模态代码。

非常感谢您的帮助。

回答

0

这个错误没有在生产版本中显示...所以如果情况变得更糟,您可以忽略它。虽然它可能发生在很多不同的情况下,并且通过用户输入改变状态/视图绝对是常见的。

首先要做的是确保您使用默认changeDetection模式,而不是使用'OnPush'模式。如果您的应用程序是您自己构建的,并且您没有在任何地方更改这些设置,那么您正在使用默认的更改检测模式,因此您很棒。

您可以将输入封装在NgForm元素中,并将提交方法放入调用onSearchDocumento方法的组件代码中,而不是绑定到模板中的keyup事件。这可能会防止错误,并可能会使模板稍微更干净。

<form #formName="ngForm" (ngSubmit)="onSearchDocumento(formName)"> 
    ... input and other elements ... 
</form> 

当您使用NgForm时,其提交方法会自动侦听用户按下Enter键。这将传递整个表单的内容(而你的情况只会是一个输入)作为名为“表格名称”的对象,你可以访问各个形式的部分与它们的标识符,即

formName.numeroDocuVar.val 

如果没有按”您可能必须导入ChangeDetectorRef并强制它在继续执行其他方法之前使用其detectChanges()方法检查更改。喜欢的东西 -

import { ChangeDetectorRef ... your other imports.... } from '@angular/core' 

在组件:

constructor(private cdr: ChangeDetectorRef) { ... 

,然后调用添加到搜索方法detectChanges:

onSearchDocumento(...) { 
    this.cdr.detectChanges(); 
    // rest of method // 
} 
+0

喜透辉!感谢您的回答,我已经尝试了您提到的所有内容,但错误仍然显示!如果您有其他想法,我将不胜感激。 – cyenque

0

我有同样的问题。 为了解决它,你应该在调用你的模态窗口之前去除焦点。

constructor(private modalService: NgbModal, private elRef: ElementRef, private renderer: Renderer) {}  
this.renderer.invokeElementMethod(this.elRef.nativeElement.ownerDocument.activeElement, 'blur'); // put this line before you call your modal in the component 
this.modalRef = this.modalService.open(this.modalNotification); 

或者你应该检查你的输入,如触摸ngOnInit。

您可以阅读关于此问题的here

相关问题