Strategies for modifying the bound value in Angular with an observable object

I am attempting to convert the offset value for a time object in the URI, which is stored in an observable object.

The issue I am encountering is:

ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '2023-11-20T00:00:00-05:00'. Current value: '2023-11-20T00:00:00-06:00'. Find more at https://angular.io/errors/NG0100

HTML code:

<ng-container *ngFor="let app of siteGroup[site.name]">
                          <ng-template #tipContent1>
                            <div class="tooltip-container">
                              {{site.name}} - {{app.description}}
                            </div>
                          </ng-template>
                          <a class="clickable" [ngbTooltip]="tipContent1" [openDelay]="200" container="body"
                            ngbDropdownItem routerLink="/site/{{site.name}}/{{app.name}}"
                            [queryParams]="{caseName: routeParams.caseName, windowSize:  routeParams.windowSize, startTime: changeCurrentParamTimezoneStartTime() , endTime: changeCurrentParamTimezoneEndtime(), equipmentTypes: routeParams.equipmentTypes}"
                            (keydown.enter)="onEnter($event)">
                            {{app.name}}
                          </a>
                        </ng-container>

The function that needs to be modified if the time object exists is

 changeCurrentParamTimezoneStartTime(){
    //initial value could be 2023-11-20T00:00:00-05:00
    if(this.routeParams.startTime){
      this.routeParams.startTime = this.routeParams.startTime.slice(0,10);

      this.routeParams.startTime = moment(this.routeParams.startTime)
                                  .utcOffset(parseFloat(this.timeZoneOffset), true)
                                  .startOf('day')
                                  .format();    

      //and the return value i want is 2023-11-20T00:00:00-06:00
      return this.routeParams.startTime;  
    }
    else{
          return;
    }
    
   
  }

  changeCurrentParamTimezoneEndtime(){
    // return null
    if( this.routeParams.endTime){

      this.routeParams.endTime = this.routeParams.endTime.slice(0,10);

      this.routeParams.endTime = this.routeParams.endTime = moment(this.routeParams.endTime)
                                .utcOffset(parseFloat(this.timeZoneOffset), true)
                                .endOf('day')
                                .format();      
      return this.routeParams.endTime;         
    }
    else{
      return;
    }
    
  }

and the observable object is initialized in ngOnInit

 this.navigationService.routeParams.subscribe(routeParams => this.routeParams = routeParams);

When I log the value, I can see that it is updated but the URI does not reflect the changes in the offset value.

Answer №1

This error message indicates that a modification has been made to the component's data after the change detection process has already been completed for the current cycle. Angular conducts change detection to ensure that the component's data remains consistent and does not unexpectedly change within a single cycle. If any changes are detected after the component has been checked, this error is thrown.

To resolve this issue in your scenario, consider adding the following code snippet at the end of the ngOnInit method:

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

export class ExampleComponent implements OnInit {

  constructor(private cdr: ChangeDetectorRef) {} // Inject dependencies here

  ngOnInit(): void {
     this.navigationService.routeParams.subscribe(routeParams => { 
       this.routeParams = routeParams
       this.cdr.detectChanges(); // Manually trigger change detection
    });
         
    this.cdr.detectChanges(); // Manually trigger change detection
  }
}

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

Building an array from scratch in Angular

Below is the URL to access the code: https://stackblitz.com/edit/ng-zorro-antd-start-xz4c93 Inquiring about creating a new array. For example, upon clicking the submit button, the desired output should resemble the following structure: "tasks": [ { ...

The setter function for a component is being triggered twice when utilizing the slice method with @Input in Angular 4

Using two-way data binding in Angular 4 to pass an array to another component can be done like this: component.ts import {Component} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component. ...

An anomaly with the checkbox editing feature in the PrimeNG table

Within my Angular 5 application, I am utilizing the PrimeNG "turbo" table component and encountering an issue while trying to edit a checkbox. If you want to learn more about PrimeNg tables, visit primeNg - table https://i.sstatic.net/ryZ2A.gif As depict ...

Enhance ngx-bootstrap's tab content with ngx-scrollbar functionality

Currently in my project, I am utilizing bootstrap 4 and ngx-bootstrap. One requirement I have is to develop a component consisting of 2 scrollable divs that can be switched by tabs. I was hoping to demonstrate a sample application on stackblitz, but unfor ...

Updating the color of specific buttons using ngFor in Typescript and Angular 8

I have successfully implemented a feature where text is displayed word by word using an ngFor directive. Within the ngFor loop, there is an if-else statement that determines whether each word should be displayed as a <span> or a <button>. Now, ...

Tips for using MatTableDataSource in a custom Thingsboard widget

After creating multiple custom Thingsboard widgets, I've discovered that I can access a significant portion of @angular/material within my widget code. While I have successfully implemented mat-table, I now want to incorporate pagination, filtering, a ...

The Disabled element does not exhibit effective styling

When we include the disabled attribute in the text element, the style does not work. Can you explain why? <input pInputText [style]="{'padding-bottom':'10px','padding-top':'10px','width':'100%&apos ...

Error in React Native Typescript: The type 'string' cannot be assigned to the type '"solid" | "clear" | "outline"'. (Error code: ts(2322))

I have integrated TypeScript with React Native in my project. import React from 'react'; import { Button } from 'react-native-elements'; import { IThemedButton } from '../../../models/themedButton'; interface IThemedButtonPr ...

Tips on utilizing storage.set() within google.maps.events.addListener(marker, 'dragend', function() { }); in Ionic 3

google.maps.event.addListener(Marker, 'click', (function(Marker) { return function() { this.storage.set('mylocation', this.Marker.getPosition()); } })(Marker)); polyfills.js:3 Uncaught TypeError: Cannot read property 'set ...

"Introducing the new Next.Js 14 sidebar featuring a sleek hamburger menu

I am in the process of developing a chat application. Currently, I have a sidebar that displays existing conversations and I would like to make it responsive by implementing open and close functionalities for mobile devices. Here is the code snippet for m ...

Transforming JavaScript code with Liquid inline(s) in Shopify to make it less readable and harder to understand

Today, I discovered that reducing JavaScript in the js.liquid file can be quite challenging. I'm using gulp and typescript for my project: This is a function call from my main TypeScript file that includes inline liquid code: ajaxLoader("{{ &ap ...

I am seeking a way to access the child infoWindow within a Google Maps marker in Angular 5

I am working on an Angular 5 application that utilizes the Angular Google Maps(AGM) library available at . I have implemented functionality where clicking on an item in a list within one component triggers the display of a child infoWindow associated with ...

Tips for Passing On Parent tabindex Value to Children

Is there a way to propagate a parent's tabindex value to all of its children without individually setting tabindex for each child? Here is an example code snippet: <div id="app"> <div tabindex="2" class="parent-sec ...

Managing asynchronous data retrieval using rxjs

Within my service, I use an Observable to load data in the constructor. Later on, this data can be accessed using a getter, which should either return the data immediately if it's available or wait until the loading process is complete. Here is an exa ...

Tips for creating a custom hook that is type safe:

When I use the custom function createUser, I've noticed that I can pass numbers instead of strings without receiving an error. Surprisingly, even if I forget to include an argument, no red squiggles appear. const [userState, createUser] = useCre ...

Modify the color of the matSnackbar

I'm having trouble changing the snackbar color in Angular using Angular Material. I tried using panelClass in the ts file and adding it to the global css, but the color remains unchanged. Any suggestions on how to resolve this? I am still new to this ...

Accessing the URL causes malfunctioning of the dynamic routing in Angular 2

I am currently working on implementing dynamic routing functionality in my Angular application. So far, I have successfully achieved the following functionalities: Addition of routing to an existing angular component based on user input Removal of routin ...

Oops! Looks like there's an unexpected error with the module 'AppRoutingModule' that was declared in the 'AppModule'. Make sure to add a @Pipe/@Directive/@Component annotation

I am trying to create a ticket, but I encountered an error. I am currently stuck in this situation and receiving the following error message: Uncaught Error: Unexpected module 'AppRoutingModule' declared by the module 'AppModule'. Plea ...

Karma struggles to identify angular directives

Our project structure is based on the Angular2-webpack-starter. The project compiles, builds, and displays in the browser without any issues. However, we encounter an error when attempting to run test cases using karma and jasmine. FAILED TESTS: XXXXXX ...