Angular - Входные данные удаляются при нажатии Enter, так как они вызывают функцию «удалить» вместо намеченного фокуса - PullRequest
0 голосов
/ 21 января 2020

РЕДАКТИРОВАТЬ : добавлен stackblitz

Я пытаюсь сделать приложение способным переключаться между вводами при нажатии клавиши ввода, чтобы его было проще вместо нажатия их. Я установил (keyup.enter)="keytab($event)" для первого и (keyup.enter)="addPeso()" для второго, так как они создаются динамически, поэтому «addPeso» создает новую пару входов. Дело в том, что каждый раз, когда я нажимаю клавишу ввода, каждый вход удаляется, как если бы он вызывал функцию deleteAllPesos (которая создает .clear ()). Я не понимаю, почему это происходит. Может быть, вы можете увидеть то, что я не вижу.

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

image

1 Ответ

0 голосов
/ 24 января 2020

Обыскав везде, я обнаружил проблему с github , сообщающую о таком поведении:

jonrimmer прокомментировал 1 ноября 2016

This стандартное HTML поведение формы, никак не связанное с Angular. Нажатие ввода при фокусированном вводе текста нажмет первую кнопку отправки в форме. Один из способов избежать этого - не использовать кнопку «Отправить» в форме. В вашем плункере добавление атрибутов type = "button" к каждому элементу кнопки предотвратит их нажатие при нажатии пользователем клавиши ввода.

...