*ngif does not control the visibility of Angular Material Progresbar

In my application, the webpage needs to display a progress bar while fetching data from multiple APIs and constructing a PDF document. For this purpose, I am using the jsPDF library to create the PDF. Below is the implementation in my template:

<div class="col-md-2 col-sm-2">
<mat-progress-bar mode="indeterminate" [value]="progressValue" *ngIf="isPrintinginProgress"></mat-progress-bar>
<Button class="btn btn-primary" style="align: right" (click)="printSelected()">Print Selected</Button></div>

The isPrintinginProgress variable is initialized at the start to hide the element and then updated to true within the printSelected() function to display the progress bar.

import {Component, OnInit} from '@angular/core';
import * as jsPDF from 'jspdf';

export class PrintViewComponent implements OnInit {
  printList: PrintPendingOrderModel[];
  isPrintinginProgress = false;

  dataSource = new MatTableDataSource<PrintPendingOrderModel>(this.printList);
  selection = new SelectionModel<PrintPendingOrderModel>(true, []);

  constructor(private apiService: ApisService,
          private utilService: UtilsService) { }
  ngOnInit() {

  }
   printSelected() {
     this.isPrintinginProgress = true; //displaying the progress bar       
     const doc = new jsPDF();    
     console.log('printing page:', page_no); 
     if (page_no < total_pages) {
        console.log('end page:', page_no);        
        doc.addPage();
     } else {
        doc.autoPrint({variant: 'non-conform'});        
        window.open(doc.output('bloburl'), '_blank').focus();
        console.log('Print Complete');       
        this.isPrintinginProgress = false; //hiding the progress bar
     }
     this.selection.clear();
   }

If I set isPrintinginProgress to true initially, the progress bar appears on the page. However, changes in the isPrintinginProgress variable do not affect the functionality of elements using *ngif for show/hide operations.

Answer №1

Choice 1

<div *ngIf="isPrintinginProgress" class="col-md-2 col-sm-2">
<mat-progress-bar mode="indeterminate" [value]="progressValue" ></mat-progress- bar>
</div>
<Button class="btn btn-primary" style="align: right" (click)="printSelected()">Print Selected</Button>

Include a div where the progress bar is located, and use ngIf to show or hide the div based on conditions.

Choice 2

<div [hidden]="!isPrintinginProgress" class="col-md-2 col-sm-2">
<mat-progress-bar mode="indeterminate" [value]="progressValue" ></mat-progress- bar>
</div>
<Button class="btn btn-primary" style="align: right" (click)="printSelected()">Print Selected</Button>

You can also utilize the [hidden] attribute for toggling visibility of elements.

Answer №2

There is a possibility that the changes are not being detected. You can try the following code snippet to see if it resolves the issue.

constructor( private cdr: ChangeDetectorRef){
}

this.isPrintinginProgress = false;
this.cdr.detectChanges();

Answer №3

Please note: If you see the message Print Complete in your console, it means that the flag is changing rapidly and you may not be able to observe the change. Consider using a timeout function.

initiatePrinting() {
 this.isPrinting = true; // display progress bar
 this.setTimeout(()=>{
 const document = new jsPDF();    
     console.log('printing page:', pageNumber); 
     if (pageNumber < total_pages) {
        console.log('end page:', pageNumber);        
        document.addPage();
     } else {
        document.autoPrint({variant: 'non-conform'});        
        window.open(document.output('bloburl'), '_blank').focus();
        console.log('Print Job Completed');       
        this.isPrinting = false; // hide progress bar
     }
 this.clearSelection();
 },3000);
}

Answer №4

Rebooting the system successfully fixed the problem of a progress bar not appearing.

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

Placing images inside a div causes them to vanish

I encountered a strange issue where the images I added to a background disappeared. .Background1{ position:relative; top:0%; left:0%; height:100%; width:100%; content:url("/assets/backgroundlayer1.jpg") } .Background2{ posi ...

What is the process of switching the dark theme on and off in an Angular application using

Looking to incorporate a bootstrap dark theme into my Angular app, but unsure of how to add the data-bs-theme="dark" attribute in the index.html file. Any suggestions? Struggling with dynamically changing the data-bs-theme attribute using Angular. Any tip ...

Using an Angular 2 filter pipe to search across multiple values

Currently, I am working on implementing a filter for a table of users using pipes. While I have successfully made it work for filtering based on one selection, I am now attempting to extend this functionality to accommodate multiple selections. It's i ...

A new object type is being introduced that allows for a dynamic number of keys and values. It also supports values that can be either a

I'm working on a project using NextJS and TypeScript. I have a function named submitFunc that needs to accept three arguments - type (string), base endpoint (string), and an object with dynamic keys and values, where the values can be either strings o ...

Using Stack and Drawer Navigations Together in React Native Navigation(v6)

I am looking to merge Stack and Drawer navigations. I have multiple screens and wish to display select screen labels in the drawer tab. <RootNavigatorStack.Navigator> <RootNavigatorStack.Screen name="DrawerTab" component={DrawerNavig ...

The error message indicates that providing a number type instead of a string type to a parameter is causing an issue

This is my code snippet const currentTimeStamp = `${(parseInt(Date.now() / 1000))}`; const [roomName, setRoomName] = useState<string>(currentTimeStamp || ''); When running in production: An error occurs stating: Argument of type ' ...

How can I effectively test static navigationOptions using Jest and Enzyme in a React Navigation and TypeScript environment?

Currently, I am developing a React Native app using TypeScript. For component testing, I rely on Jest and Enzyme. Additionally, I have integrated React Navigation into my project. On one of the screens, the navigationOptions are as follows: static naviga ...

Union does not contain the specified property in Typescript

Here are the types that I have: Foo { foobar: any } Bar { fooBarBar: any; } I want to use a function defined like this: this.api.submit(param: Foo | Bar) When trying to use it, I encountered an issue: this.api.submit(param.foobar) // does no ...

I am unable to utilize Local Storage within NextJS

type merchandiseProps = { merchandises: merchandiseType[]; cart?:string, collection?:string, fallbackData?: any }; const MerchandiseList: FC<merchandiseProps> = ({ merchandises }) => { const [cart, setCart] = useState<merchandiseType ...

Troubleshooting Angular AutoComplete's Lack of Response from Async Validator

I am looking to enhance the user experience by implementing autocomplete functionality that triggers an error and sets the FormControl to invalid when a user deletes a character from a selected value. Unfortunately, I have encountered difficulties in achie ...

Is it possible to pass additional arguments to setState other than prevState and props?

I'm currently facing an issue with my component that involves calling a function called addOption, which is defined on its parent component. This function takes a parameter 'option' from a form field and concatenates it with an array of opti ...

Tips on setting up tsconfig.json for type declarations not found in @types?

When setting up my app, I am using a tsconfig.json file to specify which typings should be used. { "compilerOptions": { "types" : ["node", "lodash", "express"] } } This configuration allows me to import typings from ./node_modules/@types/nod ...

What is the best way to flatten a 2D array using TypeScript?

If I have an array structured like this: [0]: ["id_1"]: prop1: "abc" prop2: "def" ["id_2"]: prop1: "ghi" prop2: "jkl" [1]: ["id_3"]: prop1: "mno" prop2: "pqr" ["id_4"]: prop1: "stu" ...

Invoke the login function from the service in the Angular2 component and handle any potential errors

Struggling to implement an HTTP service call in Angular2 and handle error messages? Despite trying various methods like Promises and Observables for a week, I just can't seem to make it work. Any assistance would be greatly appreciated. I am relative ...

Generating a fresh array based on the size of its existing elements is the key feature of the ForEach method

When running this forEach loop in the console, it extracts the property "monto_gasto" from an array of objects in the firebase database. Here's how it looks: something.subscribe(res => { this.ingresos = res; ...

Creating a function in typescript that returns a type based on the input parameter

type A = { aa: string; bb: number; }; type G = { <T extends keyof A>(a: T): A[T]; <T1 extends keyof A, T2 extends keyof A>(a: T1, b: T2): [A[T1], A[T2]]; // ... }; const g = {} as G; const x = g('aa'); //string const y = g ...

Incorporate an imported type as a nested component within an interface, and subsequently utilize the interface as properties within the Vue3 script

While this may appear to be a straightforward question, I have not been able to find any discussions on this topic. Currently using Vue3 with script setup Objective: In short: I am attempting to utilize a child type definition to specify one key of an in ...

What is the best way to create a universal limitation for a larger collection of a discriminated union?

Is it possible to enforce that when defining a generic class Foo<X>, where X represents a discriminated union type, X must be a superset of another discriminated union Y? In my specific scenario, I am utilizing a discriminated union to differentiate ...

Determining the chosen numeral and letter in Angular 8

I am encountering an issue with the selected option, where the name_step = "ABCD" is selected, but when the name_step = "1" is not selected. I am puzzled as to why this is happening, despite setting both as strings. Here is my code snippet: <option ...

Tips for overlaying a webpage with several Angular components using an element for disabling user interactions

I currently have an asp.net core Angular SPA that is structured with a header menu and footer components always visible while the middle section serves as the main "page" - comprised of another angular component. What I am looking to achieve is ...