简体   繁体   中英

Angular function running in loop

I have a button I want to disabled under certain circunstances, so I have configured the disabled attribute to take its value from a function result. The problem I found is that if I put a console.log inside the functions I can see it is running in a loop. Is it normal? Could be a matter of the changeDetectionStrategy?

TEMPLATE BUTTON CODE

<button mat-raised-button color="primary" (click)="documentEditForm.ngSubmit.emit()"
[disabled]="deshabilitarBotonGuardar()">Guardar</button>

FUNCTION CODE

n = 0
deshabilitarBotonGuardar(){
  this.n++
  console.log('Esto viene del control de habilitación del botón Guardar:' + this.n)
  if(this.form.invalid ||
     this.guardadoDB ||
     this.ds.modeForm == estadoFormulario.registroMostrar || 
     this.isSaving){
    return true;
  } else {
    return false;
  }
}

在此处输入图片说明

UPDATE

I have found the problem, I had two intervals to count the session time and the token time. To track them I was storing second by second the result of the two intervals in two variables in my authenticationService. I removed those intervals and now the function only runs when something changes.

The issue was that every second those variables were changing and fired angular change detection.

Yes, it is normal. Because this function is invoked every time in render phrase. Try not to use complex code for functions which used in components properties.

It's not exactly running in a "loop", but you are correct that it is due to change detection. You might consider switching to the ngOnChanges life cycle hook to check your disabled state. This way you no longer have to reference a method in your template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM