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

Encountering a compilation error while trying to utilize a union type in a function parameter within an

As stated on https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html, it is recommended to utilize multiple types for a parameter in a function (refer to the union part) /* OK */ interface Moment { utcOffset(): number; ...

Angular 4 - Resolve ngModelChange Error: Property '...'is Undefined When Binding Two Select Form

I need assistance with implementing a functionality in Angular 4. I have a JSON model that contains information about books, including their titles and authors. I want to create two select form elements (dropdowns): the first dropdown should display the ti ...

Is React Spring failing to trigger animations properly on iOS devices?

I have a code that functions perfectly on my desktop and across all browsers. Each button is designed to trigger a 4-second animation upon load or hover, initiating the playback of various videos. However, there's an issue with iOS where the video or ...

Is it possible to choose a range in ion2-calendar starting from the day after tomorrow and spanning three months ahead?

Currently, I have set up an ion-calendar utilizing the ion2-calendar plugin. The calendar is configured to disable dates prior to today's date. However, my goal is to also disable "today" and display available dates starting from tomorrow. Additionall ...

ngFor is failing to show the array data, which is being fetched from Firebase

Hi there, I understand that this question has been asked frequently, but the regular solutions are not working for me. ts handleChangeFormType(formType) { this.serverData.getData('questionnaire/' + formType) .subscribe( (response: Respons ...

Creating a new element in the DOM when a button is clicked using Angular 2+

Greetings! I am currently in the process of learning how to manipulate the DOM using Angular 2+ and my goal is to incorporate an Input field with type email when the click event is activated. Despite conducting some research via Google, I have been unable ...

Setting the background color of a button within a template in an Angular 8 component using style.background

I have been exploring the different versions of Angular and their changes. Currently, I am enrolled in an Angular course on Udemy where I have installed Angular 8. In the course, it is mentioned to use style.backgroundColor on a button inside the template ...

Failed to execute start script 'ng serve' in npm start

Let me make it clear: I'm brand new to AngularJS and pretty much any Web Technology. I consider myself a novice in the realm of Web Development. I attempted to install AngularJS, and truth be told, after numerous "Mysterious Button Clicks", I might ...

What is preventing Ionic from locating my model interface?

I recently started working with Ionic and I am using a tutorial as a guide to integrate Firebase authentication into my project. However, I am encountering an issue with the user interface that is being generated. When I run ionic serve for the first time ...

Automatically update the cart count in the header component in Angular 6 when a product is added to the cart, without the need to

I am working on an E-Commerce application using Angular 6. I am facing an issue with updating the shopping cart count in the header component whenever a product is added or removed from the cart. The cart count only updates when I refresh the page. I have ...

Issue: Module './App' not found in webpackSolution: Check if the module path is

I've decided to switch my .js files to .tsx in order to start using TypeScript. To incorporate TypeScript, I used the following command: yarn add typescript @types/node @types/react @types/react-dom @types/jest and began converting first index.tsx fo ...

How to have Angular open a PDF file in a new tab

Currently, I am working on implementing the functionality to open a PDF file in a new tab using Angular 9. The PDF file is received from an API as a blob. However, I have encountered an issue due to the deprecation of window.URL.createObjectURL(blob);. Thi ...

Incorporating Bootstrap 3 into an Angular 2 Application with Webpack

My Angular 2 project is utilizing the Webpack module bundler and I am looking to incorporate Bootstrap into the application using webpack. Bootstrap has been installed via npm, as reflected in my package.json file: "devDependencies": { "@angular/co ...

What is the process for linking a Python Flask CAS server with an Angular application?

After successfully setting up the python server (Flask to be specific) and establishing a successful connection to my CAS server, it is working flawlessly by redirecting to CAS login and returning accurate user data upon login. Here is the relevant code sn ...

What steps should I follow to ensure that TypeScript is aware of the specific proptypes I am implementing?

Is there a way to instruct TypeScript on the prop types that a component is receiving? For example, if multiple is set to true, I would like TypeScript to expect that selectValue will be an array of strings. If it's not present, then TypeScript should ...

What steps are needed to integrate a Spring Boot application with Angular 2?

After incorporating Angular 2 into my Spring Boot application, I successfully deployed all of my files. However, the routing feature is not working as expected. Below is the file structure. This setup works smoothly with a Node.js server. ...

Handling routerLink exceptions in Angular 2, 4, and 5

In my app, I am working on catching routing exceptions. There are three ways in which a user can navigate: If the user types the address directly - this can be caught easily by using { path: '**', redirectTo: 'errorPage'} in the route ...

Typescript Angular2 filtering tutorial

In Angular 2 using TypeScript, the goal is to search for matching values from an array within an object array. The intention is to filter out any objects where the 'extraService' property contains any of the values from the 'array_values&apo ...

Having issues with the Carousel feature in Bootstrap 5.3.1 while using Angular version 15

I'm currently in the process of setting up a carousel on my homepage. It seems like everything is in place, but there's something missing. The initial image, text, and arrows all display properly, but they are non-functional. I have correctly imp ...

What could be causing the dispatch function to not run synchronously within guards during the initial load?

It has come to my attention that in certain scenarios, the execution of reducers is not happening synchronously when using store.dispatch(...) as expected. This behavior seems to be isolated to CanActivate guards and during the initial loading of the appli ...