Problem with Change Detection in Angular 2

I am currently utilizing Angular 2.1.1 for my application.

Situation
Let's consider a scenario where two components are interacting with each other. The component DeviceSettingsComponent is active and visible to the user. It contains a close button as shown below:

<a class="close" (click)="closeDeviceSettings()">&times;</a>

The close button handler simply emits an event:

private closeDeviceSettings(): void {
    this.sharedService.broadcast('deviceSettingsClosed');
}

The MainComponent is listening to that event:

this.sharedService.on('deviceSettingsClosed', () => this.isDeviceSettingsOpen = false);

In the template of MainComponent:

<div class="main-device-settings" *ngIf="isDeviceSettingsOpen">
    <device-settings [device]="openSettingsData.device"></device-settings>
</div>

All seems to be working correctly in Angular 2.1.1.

Issue
Upon updating to Angular 2.2.x, there appears to be a delay of 3-5 seconds between clicking on the close button and the DeviceSettingsComponent being removed from the DOM. No code changes have been made, except for the Angular version update indicated in package.json.
It doesn't seem to be related to the event handling, as the isDeviceSettingsOpen property in MainComponent updates immediately upon clicking the close button. It appears that the change detection process might be somehow delayed.

Any insights into what might be causing this?

Update

I was able to resolve the issue by manually triggering a change detection right after updating my property like so:

constructor(private changeDetectorRef: ChangeDetectorRef) { }

ngOnInit() {
    this.sharedService.on('deviceSettingsClosed', () => {
        this.isDeviceSettingsOpen = false
        this.changeDetectorRef.detectChanges();
    });
}

This approach now ensures that the component is promptly removed from the DOM. However, I find this solution not ideal and question why it is needed...

Answer №1

A situation I recently encountered involved a colleague's project facing a similar issue. The issue stemmed from the heavy logic embedded in the component template, particularly with parsing dates from strings within a table.

Every time the button was clicked, it triggered a full refresh of the view, subsequently forcing a re-parsing of all the dates.

To troubleshoot, try temporarily removing the contents of the button's click handler to see if there is still a noticeable 3-5 second delay before the page becomes responsive again after clicking. If the delay persists, it indicates that the problem lies elsewhere and not within the handler itself.

Inspect the complexity of the logic within the view (the component template) for any potential issues.

If the root cause of the delay is indeed traced back to the logic within the view, consider relocating this problematic logic to the component itself. Then, utilize the final results of the calculations within the view to optimize performance.

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

Combining the output of several components across different services in Angular

In my current situation, I am dealing with two child components within the app component. Each of these child components relies on a different service for their results. I aim to execute these services in the onInit method of each respective component an ...

Assign the primeng dropdown's value to the model in a reactive form

I am currently encountering an issue while populating a form that contains several PrimeNg dropdowns. To simplify, let's consider an example similar to the ones provided on their website. <form [formGroup]="myFormGroup"> <p-dropdown [optio ...

Angular sets the required property only when the button is clicked

Is there a way to make a field required in Angular only when a button is clicked? Currently, the error message appears even before the user interacts with the field. I would like the error message "folder name is required" to only appear when the user cli ...

Angular 13 throws NG0301 error message, failing to display the problematic module

Can someone provide assistance? Recently, I upgraded my Angular project from version 11 to version 13: Angular: 13.2.4 ... animations, cdk, common, compiler, compiler-cli, core, forms ... platform-browser, platform-browser-dynamic, router Package ...

Issue with Nestjs validate function in conjunction with JWT authentication

I am currently implementing jwt in nest by following this guide Everything seems to be working fine, except for the validate function in jwt.strategy.ts This is the code from my jwt.strategy.ts file: import { Injectable, UnauthorizedException } from &ap ...

Retrieving class properties in typescript

I am working with a class that has numerous methods, which I refer to as myClass. When calling it, the syntax is as follows: myClass[key]() Is there a way to retrieve the valid values for key? I tried using keyof myClass, but received an error message st ...

Redirecting to different paths using Angular 6 routing

My experience with Angular is fresh, as I embark on crafting my initial Angular application tailored for an admin dashboard. The task at hand involves setting up two distinct layouts: Authentication layout (incorporating login, logout, forgot-password f ...

What is the reason behind prettier's insistence on prefixing my IIAFE with ";"?

I've encountered async functions in my useEffect hooks while working on a JavaScript project that I'm currently transitioning to TypeScript: (async ():Promise<void> => { const data = await fetchData() setData(data) })() Previously, ...

Utilizing Angular to Handle Undefined Variables in String Interpolation

Seeking a way to showcase data obtained from an external API on a webpage using Angular's string interpolation. If no data is retrieved or is still pending, the aim is to display 'N/A'. An attempt was made following this method, but encoun ...

What is the Ideal Location for Storing the JSON file within an Angular Project?

I am trying to access the JSON file I have created, but encountering an issue with the source code that is reading the JSON file located in the node_modules directory. Despite placing the JSON file in a shared directory (at the same level as src), I keep r ...

What method can I use to reach the controller of a route that has been exported to another route?

I am currently incorporating nested routes in my TypeScript project. I have set up a router named review.route.ts with the following code snippet: > review.route.ts import { createReview } from "@controller..."; const reviewsRouter = Router() as Expre ...

How to prevent Cut, Copy, and Paste actions in a textbox with Angular 2

I am currently utilizing Angular2 to prevent copying and pasting in a textbox. However, I am seeking guidance on how to create a custom directive that can easily be applied to all text fields. Here is the code snippet that successfully restricts the copy ...

Setting a dynamically addressed property within a TypeScript interface

I have a situation where I need to dynamically access an object property using a variable that represents a keyof the object type. Here's an example: interface FidelityCheckRow { P1: number; P2: string; P3: string; } const keys: (keyof F ...

Creating a unique Nest.js custom decorator to extract parameters directly from the request object

I am working with a custom decorator called Param, where I have a console.log that runs once. How can I modify it to return a fresh value of id on each request similar to what is done in nestjs? @Get('/:id') async findUser ( @Param() id: stri ...

Steer clear of using the non-null assertion operator while assigning object members

Looking for a practical method to assign object members to another object without using the non-null assertion operator "!". In the example below, consider that formData can be any JavaScript object. some.component.ts export class SomeComponent { someMo ...

Exploring Composite Types with TypeScript's `infer` Keyword

After implementing redux in my project, I found myself including the following code snippet in my store: type CombinedParamTypes<T extends { [key: string]: (state: any, action: any) => any; }> = T extends { [key: string]: (state: infer R, ...

Resolve the issue with automatically generating SCSS type definitions (style.d.ts) for Preact within a TypeScript webpack setup

Utilizing webpack with Preact 10.x (nearly identical to React) and TypeScript in the VSCode environment. Following an update from Node version 12 to version 14, there seems to be a problem where *.scss files no longer automatically generate their correspo ...

What is the best method for obtaining XML within typescript react in the bpmn-js/lib/Modeler?

After importing my BPMN XML in Model using importXML and setting bpmnModeler to bpmnModelerClone, I now need to retrieve the BPMN from bpmnModelerClone. How can I achieve this? Below is the code snippet showing how I imported XML and set bpmnModeler to bp ...

Substitute a specific text within an array of strings using Angular 2

Currently, I am working with a string array that includes elements such as age, gender, and nationality. Specifically, I am interested in replacing the element "age" with "agexxxx". Do you know of any methods to accomplish this within an Angular framewor ...

Assets failing to duplicate during ng build in production

Currently, I'm developing an application using Angular 4. I recently added a new SVG image to the assets/images folder and made the necessary changes in the angular-cli.json file as well. When I run 'ng build' locally, it successfully copies ...