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

Ways to determine the current active tab in React are:

Currently, I am facing an issue with my code involving two tabs. Upon clicking on the second tab, I want to display a specific message. However, I am struggling to determine when the second tab is selected. The main problem lies in the fact that the selec ...

Accessing the property of an object with TypeScript

I am working with an array of objects, where each object contains two properties: {key:count} When configuring my chart, I need to set the data source in this format: {meta: "unknown", value: [the count of unknown]}, {meta: "male", value: [the count of ...

Universal in Angular is malfunctioning

As a newcomer to Angular 4, I am looking to create an Angular app that is SEO friendly and supports Angular Universal (with the --universal flag after ung new or ung init). I have successfully created an Angular Universal app. However, when running the p ...

Is there a way to assign a value to an Angular-specific variable using PHP?

In the development of my Angular 4 application, I encountered an issue while receiving JSON data based on an id value through a PHP script. Upon examining the code, it seems that there should be a value passed into this.PropertiesList. examineProperties(i ...

Using ngIf to locate a substring

<ul class="list-group" *ngFor="let head of channelDisplayHeads"> <li class="list-group-item" *ngFor="let channel of channelList" ngIf="channel.channel.indexOf('head') === 1"> <strong>{{ head }}</strong> ...

A guide to implementing Typescript Generics in modifier functions

I am searching for a solution to properly enforce strong typing in the following scenario. I believe Typescript Generics might be the way to go here. interface Person { name: string; age: number; } const person: Person = { name: "John", ...

Converting an array with objects to comma separated strings in javascript using (ionic , Angular , NodeJS , MongoDB)

Retrieving specific data from an API array: let passions = [ {_id: "60a1557f0b4f226732c4597c",name: "Netflix"}, {_id: "60a1557f0b4f226732c4597b",name: "Movies"} ] The desired output should be: ['60a1557f0b4f226 ...

What is the reason TypeScript does not display an error when assigning a primitive string to an object String?

From my understanding in TypeScript, string is considered as a primitive type while String is an object. Let's take a look at the code snippet below: let s: string = new String("foo"); // ERROR let S: String = "foo"; // OK It's interesting to ...

What is the best way to showcase a diverse list with varying templates using Angular?

Looking to showcase a variety of items sourced from a service, each potentially belonging to different types. I am in search of a way to dynamically display distinct templates for each item based on its value or type. Is there a functionality that allows ...

Error TS 2322 - The property 'id' is not present in the object of type '{ id: number'

Just starting out with Angular and TypeScript. I created a model with the same properties but encountered an error and am struggling to find a solution: TS2322: Type '{ id: number; model: string; plate: string; deliveryDate: string; deadline: st ...

What causes the appearance of the "?" symbol at the beginning of the URL and triggers a reboot of the app when moving through the absolute path?

I am facing an issue. In my multi-module application with lazy loading, I encountered a strange behavior when trying to navigate between child lazy modules. Transition from top module to bottom child module works fine, but routing from one bottom child la ...

Suggestions for developing a component library for angular/react modules

I'm currently leading an initiative at my workplace to implement the use of standardized components across all our projects in order to maintain a consistent look and functionality that aligns with our brand. My main concern is figuring out how to eff ...

Exploring the contrast between string enums and string literal types in TypeScript

If I want to restrict the content of myKey in an object like { myKey: '' } to only include either foo, bar, or baz, there are two possible approaches. // Using a String Literal Type type MyKeyType = 'foo' | 'bar' | &ap ...

Dealing with the issue of incompatible types in TypeScript with Vue 3 and Vuetify: How to handle numbers that are not assignable to type Readonly<any

Currently, I am utilizing Vite 3 along with Vue 3 and Vuetify 3 (including the Volar extension and ESLint). Additionally, I am incorporating the composition API in script setup mode. Within my HTML code, I am utilizing Vuetify's v-select. Unfortunate ...

How can I populate a PrimeNG DataTable with an Array of Objects in Angular 2?

After fetching an array of objects (referred to as devices) from an API using a POST method, I successfully displayed them in a basic HTML table: <table class="table table-striped"> <thead> <tr> <th *ngFor="let property of ...

Prevent selection of past dates and times in ng-bootstrap calendar in Angular 7

HTML <ngb-datepicker (select)="onDateSelect($event)" [(ngModel)]="datePickerModel"></ngb-datepicker> <ngb-timepicker [meridian]="meridian" [(ngModel)]="time" class="fromTimePick"> </ngb-timepicker> Is it possible to restrict the ...

A guide on extracting a JSON data with a BigInt type using TypeScript

I am facing an issue with parsing a bigint from a JSON stream. The value I need to parse is 990000000069396215. In my TypeScript code, I have declared this value as id_address: bigint. However, the value gets truncated and returns something like 9900000000 ...

The error message states that the object literal can only define properties that are known, and in this case, 'tailwindcss' is not recognized in the type 'NuxtConfig'

I'm facing an issue in my nuxt.config.ts file while trying to set up a custom tailwind css path. The error I keep encountering can be viewed here. Can someone guide me on how to properly create the custom tailwind css path in my nuxt.config.ts file? ...

Creating a factory function through typhography

I have a dynamically generated list of functions that take an argument and return different values: actions: [ param => ({name: param, value: 2}), param => ({label: param, quantity: 4}), ] Now I am looking to create a function that will gen ...

Is there a way to access the Angular directive instance from the console?

ng.probe($0).componentInstance allows you to access the reference to the instance. Can we retrieve the directive instance from the console in any way? ...