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

Unusual navigation patterns in Angular

My Mean app is set up with the Angular app residing in the '/dashboard' path. The home page of the app works fine. Reloading the app returns the page it was on. Even routes with '/dashboard/anything/anything' refresh properly. However, ...

Invoking a Directive within another Directive

Feel free to check out this demo on Plunkr. I've set up a basic structure: <body ng-app="myApp"> <div ng-controller="myController"> <parent-directive></parent-directive> <child-directive></child-direc ...

Error: The property 'process' cannot be read because it is not defined

Seeking help with a code issue Any advice on best practices would be greatly appreciated. Thank you! An error has occurred: TypeError: Cannot read property 'process' of undefined myComponent.ts ProcessInfo: any | false; showSaveItems = ...

How does the highlighting feature in Fuse.js includeMatches function operate?

Currently, in my Next JS/Typescript web application, I am using the Fuse.js library. However, I am still uncertain about how the includeMatches option functions for highlighting purposes. Whenever I enable this option, I receive a matches object within the ...

The customer opts to store all images indefinitely into the data stream

I have set up a node server that captures images from a webcam at regular intervals and sends them to the client using the Delivery.js node module. Upon monitoring the browser resources in Chrome development tools, it appears that each image sent is being ...

Unable to integrate bower with gulp for automation

I am trying to get gulp to run the installation of all files listed in my bower.json. However, despite writing the code below, it is not working and I'm not seeing any errors. What could be causing this issue? var gulp = require("gulp"); var bower = ...

Turn off the background when the automatic popup box appears

I have implemented a popup box that automatically appears after 5 seconds when the site is loaded. However, if I click outside of the popup box, it closes. I want to disable the background when the popup box is displayed. If I remove the two lines of code ...

Transferring information between two components in separate Angular 4 modules

Within my application, I have defined two modules named AppModule and UserModule. I am currently encountering an issue with data sharing between the AppComponent and the LoginComponent (which belongs to the UserModule). Below is a snippet of app.componen ...

Create static HTML files using an Express server

Recently, I developed a nodejs web project using express-js and ejs. However, upon further reflection, it occurred to me that hosting it as static html files on Netlify might be more cost-effective than running it as a nodejs app on Heroku. Since the data ...

Retrieve the node environment variable within a JavaScript file

When setting the env variable in the start command within the package.json file, here is an example: package.json "scripts": { "start": "webpack-dev-server --config ./webpack.config.config.dev.js --env.mode=dev --port 4200&quo ...

Eliminate any undefined data in the popup map of Javascript

I am working with JSON data that is being displayed in a pop-up on a map. In cases where there is missing data (Visibility), the word undefined appears in the pop-up. Is there a way to remove the undefined text so that it does not show up in the pop-up? ...

Personalizing MaterialUI's autocomplete functionality

Trying to implement the material-UI Autocomplete component in my react app and looking for a way to display a div when hovering over an option from the list, similar to what is shown in this reference image. View example If anyone has any tips or suggest ...

When attempting to establish a connection with MongoClient, the function fails gracefully without generating an error

try { if (!conn) { console.log("Attempting to Connect to Atlas"); conn = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, }); console.log("Success ...

How can I implement a scroll bar in Angular?

I am facing an issue with my dialog box where the expansion panel on the left side of the column is causing Item 3 to go missing or appear underneath the left column when I expand the last header. I am looking for a solution to add a scroll bar so that it ...

during implementation of ng-repeat directive with JSON dataset

When I receive JSON data and attempt to display it using the ng-repeat directive, I encounter an error ng-dupes error <table> <tr ng-repeat="emp in empArr"> <td>{{emp.empcode}}</td> <td>{{emp.empName}}< ...

The functionality of Angular 2's AsyncPipe seems to be limited when working with an Observable

Encountering an Error: EXCEPTION: Unable to find a support object '[object Object]' in [files | async in Images@1:9] Here's the relevant part of the code snippet: <img *ngFor="#file of files | async" [src]="file.path"> Shown is the ...

What are some methods for utilizing jQuery or Javascript to dynamically modify CSS styles depending on the current URL?

I'm working on integrating a separate navigation area file with my content using PHP includes. I have this idea where I want the links in the navigation area to change color depending on the active page (current URL). Essentially, I need jQuery or Jav ...

"Enscroll – revolutionizing the way we scroll in

I recently incorporated the "enscroll" javascript scroll bar into my webpage. You can find more information about it at <div id="enscroll_name"> <ul> <li id="p1">product1</li> <li id="p2">product2</li> ...

typescriptIn React Router v5 with TypeScript, an optional URL parameter is implemented that can have an undefined

I'm currently working with react-router v5.1 and TypeScript, and I have set up the following route configurations: <Router basename="/" hashType="slash"> <Switch> <Route path="/token/:tokenName"> <TokenPag ...

Error message on Cypress with TypeScript: No test specification files detected

Encountering the error "Unable to run because no spec files were found, even though there is a .ts spec file in Cypress. Execute the command below in the terminal: npx cypress run --spec="./cypress/integration/specs/Test1.spec.ts". Attempted to run the t ...