Keep track of the input values by storing them in an array after they are

Creating an Angular application to read barcodes.

barcode-scanner.component.html

<form #f="ngForm" class="mt-3 text-center" id="myform" (ngSubmit)="onSubmit(f)">
          <div class="text-center">
            <input type="text" maxlength="13" name="barcode" class="form-control text-center mt-2" [(ngModel)]="barcode" placeholder="Barcode"> 
          </div>
        </form>

barcode-scanner.component.ts

export class BarcodeScannerComponent implements OnInit {

  barcode:string;
  codEspec:Number;
  DiaHoraEspecs:string;

  scans: Ticket[];

  constructor(private ticketlineservice: TicketlineService, 
    private activatedRoute: ActivatedRoute, private snackBar: MatSnackBar) {
      this.activatedRoute.queryParams.subscribe(params => {
        this.codEspec = params['CodEspec'];
        this.DiaHoraEspecs = params['DiaHoraEspecs'];
    });
     }

  ngOnInit() {

  }

  onSubmit(f: NgForm){    

    var element = document.getElementById("ticket");
    var scannedCodes = []; //array to store scanned barcodes
    scannedCodes.push(this.barcode);  //insert scanned barcode inside array

    for(var i = 0; i < scannedCodes.length; i++){

        if(scannedCodes[i] == this.barcode){  //compare scanned barcode with the ones inside the array

          this.snackBar.open("Ticket already scanned!",'', {
            duration: 2000,
            verticalPosition: 'top',
            horizontalPosition: 'end',
            panelClass: ['snack-error'],
            });       
            element.setAttribute("style", "visibility: hidden;");
            f.resetForm();

         }else{

    this.ticketlineservice.CheckTicket(this.barcode, this.codEspec, this.DiaHoraEspecs).subscribe(scans => {

      if(Array.isArray(scans)){
        this.scans = scans;
    }
    else if(typeof scans === 'string' ){
        this.scans = [];
    }
    else{
         this.scans = [scans];
    }

    // console.log('scans = ' + scans);
      if(scans != null){
        this.snackBar.open("Ticket is valid!",'', {
          duration: 2000,
          verticalPosition: 'top',
          horizontalPosition: 'end',
          panelClass: ['snack-success'],
          });
          element.setAttribute("style", "visibility: visible;");
        }else{
          this.snackBar.open("Ticket not found!",'', {
            duration: 2000,
            verticalPosition: 'top',
            horizontalPosition: 'end',
            panelClass: ['snack-error'],
            });       
            element.setAttribute("style", "visibility: hidden;");
        }
        f.resetForm();
    });
  }
}
  }

refresh(): void {
  window.location.reload();
}


}

Issue: I am facing a problem with my Angular application that consumes an API for checking barcode validity. The API does not provide a status indicating whether a barcode has been previously scanned or not. To address this, I have created an array to store all scanned barcodes and compare new scans with the values in the array. However, each time a new barcode is scanned, it triggers the first condition even when the barcode is not in the array. Additionally, I would appreciate any suggestions on how to persist these values so they are not lost when the user reloads the page.

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

Using Ionic 2 to fetch JSON data and display it using ngFor

My script.php generates a JSON array with data from mySQL; The next step involves retrieving this JSON array via AJAX; I am looking to dynamically create divs using ngFor, but I'm unsure of how to handle the callback for the JSON array in the Ajax s ...

What is the method to activate a click event on an input file when a button is clicked in Angular 2?

<input type="file" accept="image/*"> <button>Upload file</button> Is there a way to activate the input type=file click event using the button's click event in Angular 2? ...

I am currently working on developing a web application for a class assignment and I am unsure whether I should opt for PHP7 Non Thread Safe or Thread Safe version

While I consider myself a beginner in the realm of programming, my knowledge is limited to Python. However, I am eager to explore using PHP7+ and Typescript with Angular 2+. I've come across recommendations for these languages online, but I'm uns ...

What could be the reason for the Angular dropdown values not appearing?

Encountering an issue with binding data to a dropdown element, as the dropdown displays NOTHING SELECTED. <select #classProductTypeCombobox name="classProductTypeCombobox" class="form-control col-md-3" [(ngModel)]="classifica ...

Using Axios to invoke a function within a C# API controller

In my C# controller file, there is a function that makes an API call to retrieve placeholder data that is hardcoded locally. [Route("api/ReportingCenter/GetReportList")] [HttpGet] public class ReportController : ApiController { public async Ta ...

I'm perplexed as to why I'm receiving null for my context. Could it be due to a TypeError

Recently diving into Next Js and TypeScript, I encountered the following error: Unhandled Runtime Error TypeError: this.context is null Here's a snippet from my Layout.tsx file: import { FC } from 'react' import { Head } from 'next/d ...

Update the color of the angular material input text box to stand out

Hey there, I'm currently using Angular Material and I want to change the color of the input focus when clicked. At the moment, it's displaying in purple by default, but I'd like it to be white instead. https://i.stack.imgur.com/vXTEv.png ...

Unable to find Angular 6 Universal Application code in the view source

When examining the source of my app's home page, I noticed that the header and footer code is visible but not the body code. The body code is supposed to be contained within a <router-outlet></router-outlet>. However, when I navigate to th ...

Ionic Vue is throwing an error indicating that a property is not found on the type '{ $route(currentRoute: any): void; }'

Currently, I am developing an Ionic WebApp using Vue and TypeScript. My current task involves retrieving the current id parsed by the route. To achieve this, I have been working on a watcher: export default { data() { return { ...

NG build error: Module parsing failed due to an unexpected token - no updates made

Two days ago, out of nowhere, we started encountering build errors during deployment using GitLab CI. No alterations have been made to the build scripts, and none of the versions of NPM, NG, or Angular have been modified. The same compilation commands cont ...

How does NgRx handle updating remote data once it has been modified?

I'm struggling to grasp the inner workings of NgRx. My user list is retrieved from a Firebase store using a service like this: getAllUsers():Observable<object>{ console.log('getAllUsers'); return this.afs.collection('us ...

A tutorial on ensuring Angular loads data prior to attempting to load a module

Just starting my Angular journey... Here's some code snippet: ngOnInit(): void { this.getProduct(); } getProduct(): void { const id = +this.route.snapshot.paramMap.get('id'); this.product = this.products.getProduct(id); ...

React Typescript: The specified argument type cannot be assigned to the parameter type

Creating a Check Box Button React component has resulted in an error related to setRSelected(1) and setRSelected(2)... const [cSelected, setCSelected] = useState([]); const [rSelected, setRSelected] = useState(); const onCheckboxBtnClick = (selected ...

Having trouble extracting information from a JSON link to populate an Angular Material Table

I have successfully implemented the Angular Material Table to display data from a List. Now, I want to fetch data from a JSON URL and populate this list with that data. I've attempted several methods found online to parse the data into the list, but ...

Angular 2 - Implementing a custom base view for all components within a specific directory

I'm currently working on an app that involves user authentication. Once users are logged in, they should have access to an admin sidebar for navigation. However, there are certain pages like Login and Register that won't require the sidebar. Furt ...

What is the best way to disable the default date selection in the Angular Material datepicker?

Is there a way to prevent the default date from being selected in the angular material datepicker? By default, the datepicker selects the current date, but I would like to change this behavior. UPDATE: Just to clarify, I am looking for a solution that wil ...

Is it possible for the Chrome debugger to locate TypeScript files that have not been served by the

I am creating .js.map files to assist in debugging my TypeScript code within Chrome. The js.map files specify the correct location of the TypeScript in the "sources" property. sourceRoot is set to "", and sources represent the path to the TypeScript code ...

Reaching the maximum request threshold

Currently, I am facing an issue where users are able to upload files from the client side (using Angular 4) to the server (implemented with Spring Boot). The problem arises when a user attempts to upload more than 6 files at once. In such cases, Chrome uti ...

Error TS2694 is being caused by Electron Typescript Material-UI withStyles because the namespace "".../node_modules/csstype/index"" does not have an exported member called 'FontFace'

While I am experienced with Material-UI, I am relatively new to Electron and using React, TypeScript, and Material-UI together. Recently, I encountered an error while attempting to create an electron boilerplate code for future project initialization. Init ...

The image located in the wwwroot directory is not displaying when the <img> tag is used. What could be causing this issue in ASP.NET and Angular?

My current project is housed in a folder named 'UsedCarsShop', which contains two subfolders: Frontend Within this folder is the 'UsedCarsShopFrontend' folder, where the Angular project is located. Backend The 'CarWebShop&apos ...