The Angular component seems to be failing to refresh the user interface despite changes in value

Recently, I created a simple component that utilizes a variable to manage its state. The goal is to have the UI display different content based on changes in this variable. To test this functionality, I implemented the component and used a wait function to modify the value after a 5-second delay. Although the variable updates successfully (confirmed through console logging), it does not seem to trigger a refresh of the UI. I suspect that making the variable observable might be a solution, but I am unsure if it's necessary or if there's a simpler fix available. Below is the code for my component:

import { Component, OnInit } from '@angular/core';
import { MatSnackBar } from '@angular/material';

@Component({
  selector: 'app-export',
  templateUrl: './export.component.html',
  styleUrls: ['./export.component.scss']
})
export class ExportComponent implements OnInit {

  flowId: number;

  constructor(public snackBar: MatSnackBar) {
    this.flowId = 1;
  }

  ngOnInit() {}

  incrementFlowID() {
    this.flowId++;
    console.log(this.flowId);
  }

  openSnackBar(message: string, action: string) {
    const snackBarRef = this.snackBar.open(message, action, {duration: 5000, });
    snackBarRef.afterDismissed().subscribe(() => {
      this.incrementFlowID();
    });
  }

  initiateExport() {
    this.incrementFlowID();
    this.openSnackBar('Your pdf document is being generated', '');
  }

}

The relevant HTML snippet associated with this issue is shown below:

    <div *ngIf="this.flowId == 1">
      <button mat-raised-button (click)="initiateExport()">Create PDF</button>
    </div>
    <div *ngIf="this.flowId == 2">
      <b>Your pdf document is being created.</b>
    </div>
    <div *ngIf="this.flowId == 3">
      <b>PDF document is complete.</b> <br/>
      <a href="#">Download document</a><br/>
    </div>

Despite successful updating of the ID number during the "afterDismissed" event, changes to the variable do not seem to trigger a UI repaint. Any guidance on how to address this issue would be highly appreciated.

Answer №1

Get rid of 'this' in your HTML code.

<div *ngIf="flowId == 1">
  <button mat-raised-button (click)="initiateExport()">Create PDF</button>
</div>
<div *ngIf="flowId == 2">
  <b>Your PDF document is currently being generated.</b>
</div>
<div *ngIf="flowId == 3">
  <b>PDF generation complete.</b> <br/>
  <a href="#">Download document</a><br/>
</div>

I understand now, add this to your component. Here's a Working Link

import {Component, ViewEncapsulation, ChangeDetectorRef} from '@angular/core';

...
constructor(
public snackBar: MatSnackBar,
private ref: ChangeDetectorRef
) {
  this.flowId = 1;
}

...

openSnackBar(message: string, action: string) {
  const snackBarRef = this.snackBar.open(message, action, {duration: 5000, });
  snackBarRef.afterDismissed().subscribe(() => {
    this.incrementFlowID();
    this.ref.detectChanges();
  });
}

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

What is the best way to retrieve a soft deleted entity from typeorm in a postgreSQL database?

Can anyone help me figure out how to retrieve soft deleted documents from a PostgreSQL database using TypeORM's find, findOne, or query builder get/getMany methods? I keep getting undefined as the result. Is there a way to access these deleted values? ...

"I am facing issues with Nodejs $lookup as it is not producing the

I am looking to merge two document collections. The first collection, "prefix," contains an array of category IDs under the categoryId key, while the second collection, "categories," holds objects with a unique _id field. Here is my sample database structu ...

Having difficulty generating an Angular 5 Universal server application bundle with @ngtools/webpack

I am currently working on developing a cross-platform app using Angular 5 and WebPack without utilizing the CLI. The main issue I am facing is that I am unable to get the express application to function properly, resulting in encountering the following er ...

Identify the classification of unfamiliar items

Occasionally, you may find yourself in situations where you have to work with packages that were not designed with TypeScript in mind. For instance, I am currently using the two.js package in a React project with TypeScript strict mode enabled. It has been ...

The HTTP post method is not consistently triggering

Currently, I am in the process of developing a logout feature for angular (with a spring backend). The logout action is triggered by sending an HTTP post request to /auth/logout, where the endpoint invalidates the auth-token and refresh-token HTTP-only coo ...

What is the best way to include a router-link in a button click event in Angular 8?

Can someone please help me with adding a routing function to a button in Angular? I have already included a (click) function on the button, but how do I actually make the function navigate within the home.ts component? <button class="navbut" (click)= ...

Retrieving the name of the current page in ionViewCanEnter

While working with Ionic 2, I am currently facing a challenge in identifying the name of the page that triggered the navigation (PUSHER) before entering the destination page (PUSHEE). Within the PUSHEE page, I have an ionViewCanEnter function where I need ...

The cell must be crafted with a styling attribute to determine its placement

While working on my web app using React, I encountered a console warning: react_devtools_backend.js:4012 Rendered cell should include style property for positioning. at Grid2 (http://localhost:5173/node_modules/.vite/deps/react-virtualized.js?v=b41cc5 ...

The AngularJS2 component fails to render properly following the implementation of a new router

I recently encountered an issue with my AngularJS2 app component not loading after adding the router. Surprisingly, there was no error in the log. However, upon removing the router, the app started working again. Has anyone else faced a similar issue befor ...

Struggling with the @typescript-eslint/no-var-requires error when trying to include @axe-core/react? Here's a step-by

I have integrated axe-core/react into my project by: npm install --save-dev @axe-core/react Now, to make it work, I included the following code snippet in my index.tsx file: if (process.env.NODE_ENV !== 'production') { const axe = require(&a ...

What steps do I need to take to activate the legacy policy API for Google login?

The Legacy People API has not been utilized in project 145315848075 or it is currently disabled. To enable it, please go to and then attempt again. If you have recently activated this API, please wait a few minutes for the changes to take effect before ...

Advanced type generics in Typescript

I've hit a roadblock in my attempt to ensure type safety for a function that should take an object and return a number. Despite numerous efforts, I haven't been successful. To give you a simple example (the actual application involves more comple ...

Issue with setting {responseType: 'text'} in Angular7

Situation: When an API call is made from Angular7, Node (via express) is called to return chunked data of type string - the goal is to capture this string data and display it as a string On the Server-side: The data sent from the Node backend is in &apos ...

In Typescript, try/catch blocks do not capture return values

I am currently working on a function that performs database operations, with the implementation contained within a try/catch block. Here is an example: async function update({id, ...changes}): Promise<IUserResult> { try { //insert code here retu ...

Ways to display Leaflet pins within Angular?

I've been working with Leaflet and despite extensive research, I'm still struggling to get my marker to display on the map. I've tried all the solutions available out there, including the Angular workaround recommended by Leaflet. Currently ...

What methods work most effectively for gathering user behavior data in a web application?

While I may not be a seasoned professional web developer, I have gained some experience with front-end frameworks like Angular 4 and Vue 2.0, as well as other tools that have allowed me to create web applications (SPA) and utilize AWS Lambda for the backen ...

The $scope.eval feature in Angular 4 allows for dynamic evaluation

During the era of Angular, we utilized this framework to develop a specialized application for one of our clients. In simple terms, the application was designed to create dynamic questions and answers, even intricate ones, with specific display and validat ...

Challenge with Typescript Interfaces

Can someone help me with understanding interfaces in typescript? I am currently facing an issue with the code. The error message says: Type 'Response' is missing the following properties from type 'myObj': userId, title, id I believe ...

Having difficulty configuring my Angular .NET Core 2.1 web application correctly on GoDaddy

After deploying my netcore 2.1 Angular application using Visual Studio FTP profile to my Godaddy Host, I encountered a few issues. The deployment included the following contents: ClientApp folder wwwroot appsettings.json application.dlls web.config In t ...

Unable to retrieve values from input fields that have been established using interpolation

I'm currently developing a straightforward app that involves a form with formArray. Within the formArray, users can select a product name and amount. Once both are chosen, a third input field - total - computes the total price of the items (product pr ...