【问题标题】:Getting dynamically added textbox value in Angular在Angular中获取动态添加的文本框值
【发布时间】:2019-11-08 20:51:09
【问题描述】:

当我在 Angular 中创建输入元素时,它没有给出 value 属性。或任何其他属性,除非我手动执行。之后,它不会更新它。通过 ClassName 获取元素并说出 .getAttribute("value") 只会返回其初始值。

我已经使用node.setAttribute("value","") 手动设置了 value 属性。键入 textbox 将显示您键入的内容,但控制台记录该元素值仅显示它的初始值。它适用于getElementsByTagName,但我不能使用它

创建文本框

var node;
for (let index = 0; index < 5; index++) {
  node = document.createElement("input")
  node.setAttribute("class", "input");
  node.setAttribute("value", "");
  document.getElementById("boxesDiv").appendChild(node);
} 

在 keydown 事件中,在输入框后检查框的值

var arr = document.getElementsByClassName('input');
for (let index = 0; index < arr.length; index++) {
  if (arr[index].getAttribute("value") != "") {
    filledCount++;
    console.log("count++")
  }
} 

当它看到 textbox 有一个值/东西时,它应该控制台日志“count++”。

【问题讨论】:

    标签: angular typescript class dynamic textbox


    【解决方案1】:

    您可以按以下方式在 Angular 中执行此操作。

    import { ElementRef } from '@angular/core';
    
    export class YourComponent {
    
      constructor(private el: ElementRef) {}
    
      countFilledInputs(): void {
        let arr = this.el.nativeElement.querySelectorAll('input');
        let filledCount = 0
        for (let i = 0; i < arr.length; i++) { 
            if (arr[i].value !== "") { 
              filledCount++; 
            }
        }
        console.log("Filled Input Count => " + filledCount);
      }
    }
    

    StackBlitz Demo

    【讨论】:

    • 整个事情都在进行 keydown 事件绑定,它不允许我使用任何非默认函数或它们被调用的任何函数。我不能使用 ElementRef,因为文档本身不理解它是什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多