How to retrieve the value of a dynamically added textbox using Angular

While working with input elements in Angular, I noticed that they did not automatically come with a value property or any other properties unless manually added. Even after setting the value property manually, it would not update accordingly. Attempting to retrieve the value using getAttribute("value") would only return the initial value.

To address this issue, I had to set the value property manually using node.setAttribute("value",""). Although typing in the textbox displayed the entered text, logging the element's value showed only the initial value. While this solution worked when using getElementsByTagName, it was not ideal for my situation.

Generating Text Boxes

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);
} 

Implementing a keydown event to monitor values of the boxes after text entry

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

I expected the code to log "count++" when detecting a textbox with a non-empty value.

Answer №1

To implement this functionality using Angular methods, use the following approach.

import { ElementRef } from '@angular/core';

export class YourComponent {

  constructor(private el: ElementRef) {}

  findNonEmptyInputs(): void {
    let inputArray = this.el.nativeElement.querySelectorAll('input');
    let filledInputCount = 0;
    
    for (let i = 0; i < inputArray.length; i++) { 
        if (inputArray[i].value !== "") { 
          filledInputCount++; 
        }
    }
    
    console.log("Number of non-empty inputs => " + filledInputCount);
  }
}

View StackBlitz Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mapping a JSON array within a static method in Angular2 and TypeScript

Struggling with the syntax to properly map my incoming data in a static method. The structure of my json Array is as follows: [ { "documents": [ { "title": "+1 (film)", "is-saved": false, ...

What is the correct way to invoke a function that accepts a combination of specific string values when all I have is a regular string?

Within the TypeScript function declaration provided below, the parameter type alignment consists of unioned literals. function printText(s: string, alignment: "left" | "right" | "center") { // ... } As per the documentation ...

The variable 'React' is defined but not utilized in the code

Here's the code snippet in question: // tslint:disable import * as React from 'react'; import { Input, InputProps } from '../atoms/Input/Input'; import { FormControl } from '../hoc/FormControl/FormControl'; export const ...

Can you explain the meaning behind this TypeScript variable declaration syntax?

Can anyone explain the meaning of this code snippet: myCollection: Collection|any = null; I'm having trouble understanding it... Does it indicate that myCollection is set to type Collection, (which is an interface), with a default value of null? But ...

Can EaselJS (CreateJS) be utilized with TypeScript through parceljs?

I'm currently working on developing a game using EaselJS, and in this day and age, I've opted to use TypeScript. I have incorporated the "official" types from this source. However, I am encountering difficulties when trying to integrate it with p ...

Issues arise when Angular animations fail to function properly due to the addition of styles through the [ng

Exploring Angular animations and seeking advice. Currently, I am utilizing ngStyle to show or hide text on hover. The goal is to smoothly animate the text as it appears on the screen. Are there alternative methods to achieve the same hover effect without r ...

A guide on transforming a Firebase Snapshot child into a personalized object in a React Native environment

I'm looking for a way to retrieve data from Firebase Realtime Database and display it in FlatList format. What is the most efficient method for extracting the child value and converting it into a custom object? For example: class CustomObject { ...

Utilizing Angular 2's NgFor directive in SVG Elements

I want to use ngFor to draw an SVG Element that consists of lines. I am struggling with the implementation and need some help fixing the code. Here is what I have so far: my-component.js: import {Component} from 'angular2/core'; @Component({ ...

Utilizing Angular Services to Share Events and Reusing Components Multiple Times on a Page

My unique custom table is made up of multiple components, each emitting events using a shared service called TableEvent. These events are subscribed to by a class named TableTemplate, which facilitates communication among the different components of the ta ...

The 'isOpen' property cannot be bound to because it is not recognized as a valid property of the 'mat-autocomplete' component

Here is an example taken from the Autocomplete documentation section 13.3.5: <form class="example-form"> <mat-form-field class="example-full-width" appearance="fill"> <mat-label>Number</mat-label> ...

Comparison between Destructuring in TypeScript and JavaScript

Starting my journey with TypeScript after a background in JavaScript. In the realm of modern JavaScript, one can easily destructure objects like this: let {n,s} = {n:42, s:'test'}; console.log(n, s); // 42 test Assuming TypeScript follows su ...

How can the date pattern be set for the ngx-bootstrap Daterangepicker?

When using the pattern date for bsDatepicker, everything works perfectly fine. <input type="text" class="form-control" formControlName="birthday" bsDatepicker [bsConfig]="bsConfig" [(bsValue)]="birthday" value="{{dataNascimento | date:'dd/MM/yyy ...

Java Run-Time Polymorphism Explained

public class Super { public void methodA() { System.out.println("super A"); } public void methodC(Super arg) { System.out.println("C1"); } public void methodC(Sub arg) { System.out.println("C2"); } } // end ...

TypeScript - Issue with generic function's return type

There exists a feature in typescript known as ReturnType<TFunction> that enables one to deduce the return type of a specific function, like this function arrayOf(item: string): string[] { return [item] } Nevertheless, I am encountering difficulti ...

Can the TypeScript Event class be customized and extended?

Snippet of Code: class CustomEvent extends Event { constructor(name) { super(name); } } var customEvent = new CustomEvent("scroll"); Error Encountered During Runtime: An error occurred: Uncaught TypeError: Failed to construct 'Ev ...

Distinguish between multiple occurrences of the same component in Angular 2

I've recently started learning Angular 2 and have a query regarding components. I have created a component called "dropdownComponent" that generates dropdown components. However, when using this component multiple times, I'm unsure how to differe ...

Exploring the world of dynamic locale with Angular 5 Pipes

My current situation involves having apps created in angular 4 and I am contemplating upgrading to angular 5. After researching how locale is managed in the pipes, it appears that upgrading may not be feasible. It seems that there are two options provided: ...

Guide to specifying the indexer type of a function argument as T[K] being of type X in order for t[k]=x to be a permissible expression

Currently, I am attempting to create a function that can alter a boolean property within an object based on the provided object and property name. While I have found some helpful information here, the function body is still producing errors. Is there a way ...

How do I disable split panel on Ionic 2 login page exclusively?

I have successfully implemented the split-pane feature in my app.html file. However, I am facing an issue where the split pane is being applied to every page such as login and SignUp. Can someone please guide me on how to restrict the split pane function ...

Issue with ngbCollapse feature when attempting to collapse multiple dynamically generated divs on a single page

When dynamically generating ngbCollapse in a main loop that checks for the presence of the Sun in a JSON object, if the Sun is not there, it provides an option to Add_Sun(). Since it is within a loop, it allows adding a sun to every row. When clicking th ...