Is there a way to create numerous div elements in real-time when a click event occurs?

I've created a web application that requires the user to input a product number. Adjacent to the input field is an arrow icon that the user clicks. Upon clicking, there is validation to ensure that the entered number matches one of the valid product numbers stored in an array. If it's a match, a div containing information related to that product should be displayed and populated.

If the user enters the same number again and clicks the arrow, the same div should appear beneath the existing one. If a different valid number is entered, a new div with the corresponding product info should show up below the previous div. In case of an invalid number entry, an error message indicating the invalid input should be displayed without generating another div.

Currently, I'm using a show-hide method in my HTML file to display or hide the div based on the validity of the input number. However, I would like to generate multiple divs if the number is valid (as shown in the transactionDetails div below). I am wondering how I can achieve this functionality?

Below is a snippet of my HTML code:

<input class="numberInput" formControlName="ProductNumber" type="number" placeholder="{{'EnterNumber' | translate}}" [ngClass]="displayErrors ? 'inputRedBorder': 'input'" style="width:150px !important;"/>

    <span (click)="validateNumber()">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 8 8" style="vertical-align: middle;">
            <path d="M5 0v2h-5v1h5v2l3-2.53-3-2.47z" transform="translate(0 1)" />
        </svg>
    </span>

  <div class="transactionDetails grid" *ngIf="showResults">
    <!-- Product details here -->
</div>

And here's my validate function:

listOfValidProductNumbers = [ 
  3097165,
  6100256,
  6124380,
  2177422,
  3795377,
  6097961,
  3808804,
  6110164,
  1705466]; 

validateSKU() 
{
   const productNumber = this.transactionForm.get('ProductNumber').value;

    if (this.listOfValidProductNumbers.indexOf(productNumber) > -1 ) {
      this.showResults = true;
    } else {
      this.showResults = false;
    }
}

Answer №1

If you're looking for a solution, I recommend the following approach.

Start by creating an array of products in your TypeScript file like this:

private products: Array<product> = [];

Whenever your validation passes, add the new product to the array using the following code snippet:

validateSKU() {
   const productNumber = this.transactionForm.get('ProductNumber').value;

   if (this.listOfValidProductNumbers.indexOf(productNumber) > -1 ) {
      this.products.push(product);
      this.showResults = true;
   } else {
      this.showResults = false;
   }
}

In your HTML template, you can use *ngFor to display the contents of the array dynamically. As you add new products, Angular will automatically update the list. Here's an example:

<div class="transactionDetails grid" *ngIf="showResults">
   <div *ngFor"let product of products"> 
      <span>
           <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 8 8">
             <path d="M4 0c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm-1.5 1.78l1.5 1.5 1.5-1.5.72.72-1.5 1.5 1.5 1.5-.72.72-1.5-1.5-1.5 1.5-.72-.72 1.5-1.5-1.5-1.5.72-.72z" />
           </svg>
       </span>
       <span class="image">{{product.image}}</span>
      <span>
        <div class="itemDescriptionText-regular">{{product.number}}</div>
        <div class="itemDescriptionText-regular">{{product.description}}</div>
        <div class="itemDescriptionText-bold">{{product.style}}</div>
     </span>
     <span>
    </span>
    <span>
        <div style="padding-left:20px;padding-bottom:10px;">Price </div>
        <div><input class="transactionInput" placeholder="{{'EnterPrice' | translate}}"/>x</div>
    </span>
    <span>
       <div style="text-align:center;padding-right:30px;padding-bottom:10px;">Qty</div>
       <div style="text-align:center;">
        <input type='number' name='quantity' min=0 oninput="validity.valid||(value='');" class='qty'/>
    </span>
    <span>
    <div style="text-align:center;">
       Total Price 
    </div>
    <div><br></div>
    <div style="text-align:center;">
        {{totalAmount}} 
    </div>
    </span>
  </div>
</div>

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

Uploading Files to the Server with Angular 2 and ExpressJS

In my Angular-2 project, I am currently working on uploading files to the server. The code snippet provided below showcases how the file is uploaded: My main question pertains to linking these uploaded files to specific mongodb documents. How can I achiev ...

I encountered an issue while generating a crypto address on the Waves blockchain using the @waves/waves-crypto library in TypeScript

Encountering an issue with finding "crypto-js" in "@waves/waves-crypto". Despite attempts to uninstall and reinstall the module via npm and importing it using "*wavesCrypto", the error persists within the module's index.d.ts file. I am attempting to ...

Navigating back to the top of a webpage within an Angular iframe on Safari desktop

One of my challenges involves an Angular 5 application which is embedded into an Iframe on various sites to create an application form. Whenever a user clicks 'Next' to move to the next section of the form, I require the page to scroll back to th ...

Which Angular tools should I be using: map, pipe, or tap?

When my component initializes, I retrieve data from the server import {Rules} from "../../interfaces/interfaces"; rules: Rules ngOnInit() { this.tt = this.rulesService.getUserClientRules().subscribe( t => { console.log(t) con ...

Cross-origin resource sharing problem (Backend developed in Express, Frontend in Angular)

I am currently utilizing Angular for my front-end development and Express for the back-end. I encountered a CORS issue with one of multiple API endpoints that have similar configurations: Failed to load http://localhost:3000/api/deletePost: No 'Acc ...

Utilizing the <HTMLSelectElement> in a Typescript project

What exactly does the <HTMLSelectElement> do in relation to a TypeScript task? let element = <HTMLSelectElement> document.querySelector('#id_name'); The HTMLSelectElement interface, similar to the one mentioned in TypeScript, is exp ...

The dropdown navigation bar fails to close upon being clicked

I'm currently facing an issue with the navbar in my project. The bootstrap navbar doesn't close automatically after clicking on a link. I have to move my mouse away from the navbar for it to close, which is not ideal. Additionally, I'm worki ...

Is there a way to animate in Angular 4 when the page

When a user lands on an album page, I want the album photo to smoothly slide to the right as the page loads. How can I achieve this effect? Here is the animation code snippet: animations: [ trigger('slide-in',[ state('out', ...

Why won't my boolean value in the Angular service reflect in the HTML code?

For my project, I am utilizing a stepper and I need to display or hide a div based on the selected product. However, I am encountering an issue where the HTML isn't updating when I try to call the done() function. .service public beneficiary = true; ...

Unit testing of an expired JWT token fails due to the incorrect setting of the "options.expiresIn" parameter, as the payload already contains an "exp" property

I am having trouble generating an expired JWT token for testing purposes and need some guidance on how to approach it. How do you handle expiration times in unit tests? This is what I have attempted so far : it('should return a new token if expired& ...

Definitions for nested directories within a main index.d.ts

We have developed custom typings for the latest version of material-ui@next and successfully included them in the library during the last beta release. For those interested, you can access the index.d.ts file here. However, there seems to be a problem wi ...

Issues with compiling arise post downloading the latest Angular 2 quickstart files

My Angular 2 project was running smoothly on version 2.3, but I decided to upgrade to version 2.4. To do so, I downloaded the latest quickstart files from https://github.com/angular/quickstart After replacing my tsconfig.json, package.json, and systemjs.c ...

insert a gap between two elements in the identical line

Is there a way to create spacing between two text fields in the same row? I have tried using margins, paddings, and display flex in the css file but haven't been successful. import "./styles.css"; import TextField from "@material-ui/cor ...

Executing TypeScript Mocha test cases using ES6 modules

Setting up mocha tests for the TypeScript App in my Rails application has been a bit of a challenge. Initially, I added a basic test to kick things off, but encountered the following error: /home/bernhard/Programs/ruby/cube_trainer/jstests/utils/optional. ...

Manipulate the elements within an array, make changes, and then insert

In the array called newData, I am trying to add one more element with Rank 1. However, the issue is that the Rank value is getting updated for both records. The desired behavior is to have Rank set to 1 for the second record and have the first record' ...

Custom filtering for a RadListView with a unique search term

Can a filtering function be passed to an Angular Nativescript RadListView that can access the local variable 'searchTerm'? The provided sample seems to suggest using a static search term, but I want to modify it based on user input. Different Ap ...

Disable TS4023 error in TypeScript: Unable to name external module "xyz"

//custom-slice.js import { createCustomSlice } from '@my/data-toolkit'; /* ***********************For Managing all the divisions data****************************** */ export const divisionDataSlice = createCustomSlice({ name: 'divisionda ...

The module '@types/googlemaps/index.d.ts' cannot be found

I'm working on integrating the Google Maps API into my Angular project and ran into some issues. Here's what I did to install the necessary npm packages: npm install @agm/core --save-dev npm install @types/googlemaps --save-dev Next, I added th ...

The proxy is unable to access the method within the subclass

Issues are arising as I attempt to utilize a Proxy. The structure of my class is as follows: export class Builder { public doSomething(...args: (string | number | Raw | Object)[]): this { // Do stuff return this } } export class M ...

When using Router.push() in next.js, the error TypeError: products.map is not a function may arise

Currently, I am implementing redux saga in my project. Here is how the state looks: const productList = useSelector((state: RootState) => state.productList); const { loading, error, products, page, pages } = productList; In the useEffect hook, I dispa ...