Problem: "Function in ngFor runs multiple times without stopping"

0

HTML:

<input #inputCodigo type="text" (keyup)="searchProductoBarCode($event)">
  </div>
</article>
<article *ngIf="proforma && proforma.productos.length">
  <table #tableDispatch tabindex="-1" [attr.role]="role-table" appScrolling [data]="productosDespachados"
         (selected)="productoSelected=$event">
    <thead>
    <tr>
      <th>Código</th>
      <th>Producto</th>
      <th>Cantidad</th>
      <th>Fracción</th>
      <th>P.unitario</th>
      <th>P.total</th>
      <th>Stock</th>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor="let p of productosDespachados; let i=index" [class.selected]="onSelected(p,i)">
      <td>{{ p.prod_codigo }}</td>
      <td>{{ p.prod_descripcion }}</td>
      <td><input type="text" (keyup)="onKeyDownInput($event,i)" #inputsCantidad></td>
      <td>{{ p.prec_vta_final }}</td>
      <td>{{ getPrecioFinalv2() }}</td>
      <td>{{ p.prod_stock_cantidad }}</td>
    </tr>
    </tbody>
  </table>

Function onSelected() , repeats multiple times without stopping, and slows my application, the function onSelected() , returns true or false depending on the case:

onSelected(producto, index) {
const result = Object.is(producto, this.productoSelected);
if (result) {
  this.inputsFraccion.toArray()[index].nativeElement.focus();
  }
    return Object.is(producto, this.productoSelected);
}
    
asked by Luis Eduardo Farfan Melgar 15.01.2018 в 21:20
source

1 answer

1

Explanation

This happens to you because:

[class.xxx] (the same occurs with [style.xxx.yy] ) are special Angular syntax where:

[class.my-class]="expresión"

Add (or remove) the CSS class "my-class" to (or from) the element depending on whether the results of the expression are true or false .

Problem:

What happens is that when you put a function in that expression, it is executed repeatedly to check if it changes (in the same cycle as ngOnChange() ). To solve this, assign a Boolean variable which you handle, then in each execution of ngOnChange() only check if I change the value of said variable.

Solution:

(alternative to onSelected(p,i) and recommendation)

(selected)="productoSelected=$event" Not a good practice, since it can give you problems at the moment of build --prod , I recommend you perform a function that receives $event and assign its value and right here you could add the focus for your input, with something like the following:

const index = productosDespachados.indexOf(productoSelected);
this.inputsFraccion.toArray()[index].nativeElement.focus();
    
answered by 15.01.2018 / 22:28
source