Callback after completion of a for loop in Angular TypeScript

During the execution of my javascript async function, I encountered a situation where my printing code was running before the div creation. I needed to ensure that my print code would run only after the completion of the for loop, but I struggled to find a solution.

This is the method I am using:

AllShipmentPrint() {
    for (let index = 0; index < this.ShipmentList.SuppOrderLines.length; index++) {
      const element = this.ShipmentList.SuppOrderLines[index];
      for (let index2 = 0; index2 < (element.Amount / element.SetCount); index2++) {
        this.BarcodePrintList.push({ Barcode: element.Barcode, FirmModelCode: element.FirmModelCode, ColorCode: element.Color.ColorCode, ColorName: element.Color.ColorName, SuppModelCode: element.SuppModelCode, SizeList: element.SizeList, SetCount: element.SetCount });
      }
    }
    const printContent = document.getElementById("componentID");
    const WindowPrt = window.open('', '', 'left=0,top=0,width=900,height=900,toolbar=0,scrollbars=0,status=0');
    WindowPrt.document.write(printContent.innerHTML);
    WindowPrt.document.close();
    WindowPrt.focus();
    WindowPrt.print();
  }

This is the Print Code section:

  const printContent = document.getElementById("componentID");
    const WindowPrt = window.open('', '', 'left=0,top=0,width=900,height=900,toolbar=0,scrollbars=0,status=0');
    WindowPrt.document.write(printContent.innerHTML);
    WindowPrt.document.close();
    WindowPrt.focus();
    WindowPrt.print();

Below is the html code being used:

<div id="componentID">
    <div *ngFor="let item of BarcodePrintList" style="margin-top: 10px;">
        <div style="display: -webkit-inline-box;">
            <div>
                <span style="font-size: 9px;">Model : {{item.FirmModelCode}}_{{item.ColorCode}}
                    {{item.ColorName}}</span>
                <div style="display: flex;">
                    <table style="font-size: 8px;text-align: center;">
                        <thead>
                            <tr>
                                <th *ngFor="let size of item.SizeList">{{size.PropValName}}</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td *ngFor="let size of item.SizeList">{{size.Amount}}</td>
                            </tr>
                        </tbody>
                    </table>
                    <span style="font-size: 12px;margin-top: 11px;margin-left: 11px;">SET : {{item.SetCount}}</span>
                </div>

            </div>

        </div>
        <div style="float: right;">
            <img width="80px" height="40px" src="http://scm.vipstendo.com/assets/images/logo.png" alt="">
        </div>
        <div style="text-align: center;">
            <ngx-barcode [bc-value]="item.Barcode" [bc-font-size]="10" [bc-width]="1.5" [bc-height]="30"
                [bc-display-value]="true"></ngx-barcode>
        </div>
        <div>
            <span style="font-size: 10px;">{{item.SuppModelCode}}</span>
        </div>
    </div>
</div>

Answer №1

To ensure the execution after a re-rendering, a simple approach is to encapsulate the remaining code within an empty setTimeout:

setTimeout(() => {
  const contentToPrint = document.getElementById("componentID");
    const printWindow = window.open('', '', 'left=0,top=0,width=900,height=900,toolbar=0,scrollbars=0,status=0');
    printWindow.document.write(contentToPrint.innerHTML);
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
})

Although there are alternative techniques that may be more effective, they often necessitate a deeper understanding of your application.

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

Utilize Windows Phone to Encode NFC Tag

I am currently working on writing and reading NFC tags using the ProximityDevice class on Windows Phone 8.1. Here is the code snippet I'm using to write the tag... var dataWriter = new Windows.Storage.Streams.DataWriter(); dataWriter.unicodeEncoding ...

Encountering an issue with the default task in gulp, an error is displayed in Gitbash stating: "Task must have a name that is a string

Upon running the command 'gulp' in gitbash, an error is being displayed for the last line of the code, stating: throw new Error('Task requires a name that is a string'); Error: Task requires a name that is a string "use strict"; var g ...

What is the best way to iterate through an ID using jQuery?

After pulling the list of doctors in my area from the database and displaying it on my webpage, I now want to load each doctor's "About" content inside a Bootstrap modal. I added an "about" column within the same database table where the doctors' ...

Struggling to make antd compatible with my create-react-app project

Exploring ant.design with create-react-app piqued my interest, so I decided to follow the steps outlined in the antd documentation. https://ant.design/docs/react/use-with-create-react-app npx create-react-app antd-demo npm add antd Within the app.js fil ...

The Google Books API has reached its limit for requests

Encountering a rate limit exceeded error from the Google Books API while using this demo: To reproduce, open the developer console in Chrome and perform some searches. The rate limit errors will be displayed in the console. [],"lazyUpdate":null},"status" ...

Is Apollo Client in NextJS failing to refresh data post mutation?

On this page, you can create a new User const [createType, { loading, data }] = useMutation(CREATE_USER_CLASS) //mutation query const createUserClass = async (event) => { event.preventDefault(); try { const { data } = await createType({ ...

Why am I unable to utilize an array in this manner in JavaScript, and what is the method for accessing the array using a calculated number?

var nodesXY = ['15% 15%','30% 16%','19% 42%','39% 80%',]; var number = ["0","1","2","3","4","0","0","0"]; //some loop AccesNodes(number[1]); function AccesNodes(number){ console.log(number); // ...

Identify the location of the mouse and activate a specific function based

Tracking the x-coordinate of the mouse is crucial in this scenario. When the mouse approaches a specific threshold (250px) towards the left edge of the window, it should trigger the function "openNav." The function should close when the mouse moves away fr ...

Exclude basic authentication for a specific route

Using node, express and connect for a simple app with basic HTTP auth implemented. The code snippet below shows part of the implementation: var express = require('express'), connect = require('connect'); app.configure = function(){ ...

Ways to refresh Prism.js upon ngModel update in Angular 5

Currently, I am in the process of developing a CMS and facing an issue with re-rendering Prism.js to display syntax highlighting in the preview whenever there is a change in the body of the article. Below is the template code: <textarea [(ngModel ...

Modifying the status of a RadDataForm Switch editor through code

I'm working on a new angular + nativescript project that relies on the RadDataForm plugin to create forms. I have set up a source object to initialize the form editors, which is functioning correctly. One of the editors is a switch element that I want ...

Making rapid formatting changes by rearranging the positioning of words in Javascript

Struggling to untangle my complex code, I'm unable to make the necessary adjustments. Here's what I have: var stocks= [ ["Beef (80/20) raw","oz",115.4451262,3.293742347,72,"4.85 gallons","5.65 pounds","0 - ",2.142,19,20,"0.0001275510204"," ...

Searching for results using the .find() method may yield elements that do not meet the specified search criteria

Utilizing the .find() method on my JSON object called records: [ { "_id": "61f9da9fcc6888f201f722cb", "firstName": "joe", "lastName": "jergen", "email": "<a hre ...

The delivery person is not receiving a reply after making the delivery

When using Express/Node and Postgres with the 'pg' package, the following code snippet is used: const createEvent = (request, response) => { console.log(request.body); const { type, location, current_attendees ...

Styling multiple checkbox items in an Angular Material Autocomplete

Is there a way to adjust the height of autocomplete multiple checkbox items in Angular Material? I'd like it to look like this With a line item height of 18px But instead, it looks like this when using multiple checkboxes With a different checkbox ...

Are certain browsers unable to play dynamically generated HTML5 audio files?

While working on my project, I encountered an issue with creating and controlling an audio element in JavaScript. The element works perfectly fine in Firefox, Chrome, and Opera; however, it fails to function properly in IE and Safari. In these browsers, ...

Any recommendations for building HTML in an iOS UIWebView?

When using a UIWeb view, how can I create HTML content? For example, I have some header html code. Then, I would like to include a JavaScript script and pass data to it. Once the JavaScript is injected, I want to add the remaining HTML content from a .html ...

How can I make <p> elements change color when scrolling?

My Goal I aim to bring attention to the <p> element as the user scrolls on the page. Initially, the opacity is set to 0.3, but I want it to change to 1 gradually as the user scrolls down. My Attempt window.onscroll = function {scrHL}; fu ...

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

Retrieve a single document using Angularfire2 without setting up a listener

I'm facing an issue with angularfire2 v6 and angular 11. Specifically, I am attempting to retrieve a single document from the users collection based on their email without utilizing valueChanges() or snapshotChanges(). Realtime updates are not necessa ...