1

EDIT: Added a stackblitz

I'm trying to make the app capable of jump between inputs on enter key press, so its easier instead of clicking them. I have set (keyup.enter)="keytab($event)" for the first one and (keyup.enter)="addPeso()" for the second one as they are created dynamically, so "addPeso" creates a new pair of inputs. The thing is, each time I press enter, every input is deleted, as if it was calling the deleteAllPesos function (which makes a .clear()). I don't understand why is this happening. Maybe you can see something I don't.

ts:

import { Component, OnInit, HostListener } from "@angular/core";
import { resetFakeAsyncZone } from "@angular/core/testing";
import { Contenedor } from "../models/contenedor";
import { FormArray, FormBuilder } from "@angular/forms";
import { FormGroup, FormControl } from "@angular/forms";

@Component({
  selector: "app-contenedores",
  templateUrl: "./contenedores.component.html",
  styleUrls: ["./contenedores.component.css"]
})
export class ContenedoresComponent implements OnInit {
  public arrayprueba: Array<any>;
  public JSONFormulario: any;
  public maxArrayP: Array<number>;
  public maxArrayN: Array<string>;
  public pesos_ordenados: Array<any>;
  public pesos1: Array<number>;
  public pesos2: Array<number>;
  public contenedor: Contenedor;
  public contenedores: Array<Contenedor>;
  public capacidad1: number;
  public maxCasas: number;
  public mcArray: Array<any>;
  public inputsPeso: Array<number>;
  public inputsNombre: Array<string>;
  public dummyCounter: Array<number>;
  public Pesos_de_un_contenedor: Array<any>;
  public cap: number;
  public formulario = this.fb.group({
    capacidad: ["5"],
    maxcasas: ["3"],
    pesos: this.fb.array([
      this.fb.group({
        peso: this.fb.control(""),
        nombre: this.fb.control("")
      })
    ])
  });

  get pesos() {
    return this.formulario.get("pesos") as FormArray;
  }

  constructor(private fb: FormBuilder) {
    this.JSONFormulario = "";
    this.maxArrayP = [];
    this.maxArrayN = [];
    this.inputsPeso = [];
    this.dummyCounter = [];
    this.inputsNombre = [];
    this.pesos1 = [];
    this.contenedor = new Contenedor();
    this.contenedores = [];
    this.capacidad1 = 24300;
    this.maxCasas = 3;
    this.Pesos_de_un_contenedor = [];
    this.pesos_ordenados = [];
    this.cap = this.formulario.controls.capacidad.value;
  }

  addPeso() {
    this.pesos.push(
      this.fb.group({
        peso: this.fb.control(""),
        nombre: this.fb.control("")
      })
    );
  }

  deleteAllPesos() {
    this.pesos.clear();
    this.showPesos();
  }

  deletePeso(este: number) {
    this.pesos.removeAt(este);
    this.showPesos();
  }

  @HostListener("document:keyup", ["$event"])
  showPesos() {
    this.pesos_ordenados = [];
    this.contenedores = [];
    for (var i = 0; i < this.pesos.controls.length; i++) {
      if (this.pesos.at(i).value.peso) {
        if(this.pesos.at(i).value.peso<= this.formulario.controls.capacidad.value){
        this.pesos_ordenados[i] = {peso: this.pesos.at(i).value.peso,nombre: this.pesos.at(i).value.nombre};
      }else{
        this.pesos.at(i).value.peso
      }
      }
    }
    this.pesos_ordenados = this.pesos_ordenados.sort(function(a, b) {
      return b.peso - a.peso;
    });
    this.CleanShowinConsole(this.pesos_ordenados);
if(this.pesos_ordenados[0]) console.log("EL FORMULARIO" + this.pesos_ordenados[0].peso);
   /*  for (var z = 0; z < this.pesos_ordenados.length; z++) {
      this.maxArrayP = [];
      this.maxArrayN = []; */

      this.maxArrayP = [];
      this.maxArrayN = [];
      while (this.pesos_ordenados.length > 0) {  

        if(this.pesos_ordenados[0].peso){
         if (Number(this.pesos_ordenados[0].peso) + Number(this.maxArrayP.reduce(function(a, b) {return Number(a) + Number(b);}, 0)) <= this.formulario.controls.capacidad.value) 
        {
          this.maxArrayP.push(this.pesos_ordenados[0].peso);
          this.maxArrayN.push(this.pesos_ordenados[0].nombre);
          this.pesos_ordenados.shift();
          if(this.pesos_ordenados.length<=0){
            this.contenedor = new Contenedor(this.maxArrayP,this.maxArrayN,this.formulario.controls.capacidad.value);
            this.contenedor.crearMapa(this.maxArrayP,this.maxArrayN);
            this.contenedores.push(this.contenedor);
          }
        }else{
          this.contenedor = new Contenedor(
            this.maxArrayP,
            this.maxArrayN,
            this.formulario.controls.capacidad.value
          );
          this.contenedor.crearMapa(this.maxArrayP,this.maxArrayN);
          this.contenedores.push(this.contenedor);
          this.maxArrayP = [];
          this.maxArrayN = [];
        }
      }
      }

    console.log("LISTA DE CONTENEDORES:");
    for (let i = 0; i < this.contenedores.length; i++) {
      console.log("CONTENEDOR" + i + ": " + this.contenedores[i].$pesos);
    }
  }

  private CleanShowinConsole(arrayordenada: any) {
    console.clear();
    for (var i = 0; i < arrayordenada.length; i++) {
      console.log(arrayordenada[i]);
    }
  }

  keytab(event){
    let element = event.srcElement.nextElementSibling; // get the sibling element

    if(element == null)  // check if its null
        return;
    else
        element.focus();   // focus if not null
  }

  ngOnInit() {}
}

html

<div [className]="divformulario">
  <img src="../../assets/img/logo.png" />

  <form [formGroup]="formulario">
    <div [className]="form - subconjunto - horizontal">
      <mat-form-field  style="width:4vw">
        <mat-label>Capacidad</mat-label>
        <input matInput type="number" formControlName="capacidad" />
      </mat-form-field>

      <mat-form-field style="width:4vw">
        <mat-label>Máx.casas</mat-label>
        <input matInput type="number" formControlName="maxcasas"  />
      </mat-form-field>
    </div>
    <div formArrayName="pesos">
      <div [className]="form - subconjunto - horizontal">
        <button mat-stroked-button color="primary" (click)="deleteAllPesos()">
          <mat-icon>delete_sweep</mat-icon> Resetear
        </button>  
        <button mat-flat-button color="primary" (click)="addPeso()">
          <mat-icon>add</mat-icon> Añadir peso
        </button>
      </div>
      <div
        *ngFor="let peso of pesos.controls; let i = index"
        [formGroupName]="i"
        [className]="form - subconjunto - horizontal"
      >
        <mat-form-field>
          <mat-label>Peso</mat-label>
          <input
            matInput
            [style.color]="
              pesos.at(i).get('peso').value > formulario.get('capacidad').value
                ? 'red'
                : 'black'
            "
            type="number"
            formControlName="peso"
            autofocus
            (keyup.enter)="keytab($event)"
          />
        </mat-form-field>
        <mat-form-field>
          <mat-label>Casa</mat-label>
          <input matInput type="text" formControlName="nombre" type="text" (keyup.enter)="addPeso()"/>
        </mat-form-field>
        <button mat-mini-fab color="primary" (click)="deletePeso(i)">
          <mat-icon>delete_forever</mat-icon>
        </button>
      </div>
    </div>
  </form>
</div>

<div id="contenedores">
  <div *ngFor="let contenedor of contenedores; let i = index">
    <mat-card>
      <mat-card-header>
        <mat-card-title>Contenedor {{ i + 1 }}</mat-card-title>
        <mat-card-subtitle>
          LLeno: {{ contenedor.pesoTotal }} | Sobrante:
          {{ contenedor.sobrante }}
          </mat-card-subtitle>
      </mat-card-header>
      <mat-card-content>
        <div *ngFor="let datos of contenedor.datos | keyvalue;">
          {{datos.key}}{{datos.value}}
        </div>
      </mat-card-content>
    </mat-card>
  </div>
</div>
Germán
  • 1,007
  • 1
  • 7
  • 20
  • Please provide a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). There is too much code here to go through. – ViqMontana Jan 21 '20 at 10:04
  • https://stackoverflow.com/questions/53690973/change-behaviour-of-enter-key-in-a-phone-angular-5/53691367#53691367 – Eliseo Jan 21 '20 at 10:07
  • I put a link on the main post, however is it not working properly as this online editor is not finding the material components... And I'm a begginner so I don't know how to make it work. – Germán Jan 23 '20 at 16:05

1 Answers1

3

After searching everywhere, I found a github issue declaring this behaviour:

jonrimmer commented on 1 Nov 2016

This is standard HTML form behaviour, nothing to do with Angular. Pressing enter in a focused text input will click the first submit button in the form. One way to avoid it is not to have any submit button in the form. In your plunker, adding type="button" attributes to each button element will prevent them being clicked when the user presses enter.

Germán
  • 1,007
  • 1
  • 7
  • 20