The Angular expression has been modified after being examined

I've encountered a common error in my Angular application, but I'm struggling to pinpoint why it's happening and how to resolve it. I've attempted various approaches such as using setTimeout, delay(0), and switching to different hooks, but none seem to work for me.

Issue Description:

The problem arises when I try to add a single product from a list of products to the cart with selected items //product.list.component.ts

  addToProductCart(product: IProduct) {
    this.productsService.addProductToSelectedProducts(product);
  }

The service implementation is as follows:

//product.service.ts

@Injectable({
  providedIn: 'root'
})
export class ProductsService {
  selectedProducts: BehaviorSubject<IProduct[]> = new BehaviorSubject<IProduct[]>([]);
  product = this.selectedProducts.asObservable();
  
  ...
}

When a product is selected on the header, the product count increases and is displayed on the cart icon:

//header.component.html

      
      ...

//header.component.ts

  
    ...

If the header cart icon is clicked, a dialog displaying the selected product is opened. If there are no selected products, an empty cart placeholder should be displayed:

//cart-details.component.html

     
     ...

//cart-details.component.ts


  export class CartDetailsComponent implements OnInit, OnDestroy {

    ...
    
  }

The <ng-template #emptyCart> displays correctly when the cart is empty, but an error related to 'loading-background' occurs, possibly originating from ngx-ui-loader library used in app.module:

//app.module

 
  (...)
  import { NgxUiLoaderModule, NgxUiLoaderHttpModule, NgxUiLoaderConfig, SPINNER, POSITION, PB_DIRECTION } from 'ngx-ui-loader';

  imports: [
  ...
      NgxUiLoaderModule.forRoot(ngxUiLoaderConfig),
      NgxUiLoaderHttpModule,
  ]

Any insights on what might be causing this issue and how to address it would be greatly appreciated. Unfortunately, attempts to reproduce the problem on stackblitz have been unsuccessful so far. Here's the link for reference: https://stackblitz.com/edit/angular-h3xyop?file=src%2Fapp%2Fproduct-list%2Fproduct-list.component.ts

Answer №1

The reason for this issue is that your view has changed after rendering. To resolve this, you should utilize changeDetectorRef to detect changes. Include it in the constructor like so:

constructor(private ref: ChangeDetectorRef) {}

Then, after making a change, you can add:

this.ref.detectChanges();

For more information, you can visit https://angular.io/api/core/ChangeDetectorRef

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

Encountering an error when using JSONP with a period in the callback function

I am currently facing an issue with making an ajax jsonp call. It seems that the json returned contains a dot in the callback function, as shown in the example below: ABCD.render_section({ "page": { "parameters": { "pubDate": "2013-06-05 00:00:00.0", ...

PHP is unable to retrieve the formData object sent via ajax

I've been experimenting with sending a formData object to PHP (I'm following a tutorial at this link), but I'm encountering some obstacles. Firstly, I create the formData object and fill it with: var formdata = new FormData(); formdata.appe ...

ES6: The attribute 'selected' is not found on the data type 'Object'

While attempting to convert the JS code from 'AMcharts4 codepen pre selecting areas' into ES6, I encountered an error. Error TS2339: Property 'selected' does not exist on type 'Object'. Here is the code snippet that I am l ...

Implementing an onclick event listener in combination with an AJAX API call

I'm really struggling with this issue. Here's the problem I'm facing: I have a text area, and I need to be able to click on a button to perform two tasks: Convert the address text into uppercase Loop through the data retrieved from an API ...

Angular Material Spinner with Custom Image Icons - (mat-spinner)

I have successfully implemented the mat-spinner in my project with configurable changes like color and mode of spinning. However, I am now looking to add an image icon, specifically the logo of a brand or company, inside the spinner. How can I achieve this ...

Xstream produced a JSON response for a collection of objects

Utilizing Xstream for generating JSON in my application. Utilizing JSON for ajax support as well. When attempting: xstream.alias(classAlias, jsonModel.getClass()); //Note classAlias="records" responseStream.println(xstream.toXML(jsonModel)); where j ...

Error: JSON at position 1 is throwing off the syntax in EXPRESS due to an unexpected token "

I'm currently utilizing a REST web service within Express and I am looking to retrieve an object that includes the specified hours. var express = require('express'); var router = express.Router(); /* GET home page. ...

What is the process of exporting a module that has been imported in ES6?

Here are 3 code snippets: // ./src/index.ts const myApp = { test: 1, ... } export default myApp // ./src/app.ts import myApp from './src/index' export default myApp // ./index.vue import { example } from './src/app.ts' console.l ...

What steps can I take to remove the dark areas in my see-through material?

While displaying a 3D shoe model in the browser using three.js, I encountered an issue with a half-transparent material set for the heel. The problem arises when I use the orbitControls in the project and rotate the model to a certain angle, which then rev ...

RxJS: Transforming an Observable array prior to subscribing

I am retrieving data (students through getStudents()) from an API that returns an Observable. Within this result, I need to obtain data from two different tables and merge the information. Below are my simplified interfaces: export interface student Stude ...

Enhancing Bootstrap 5 with JavaScript

I am relatively new to creating webpages and have recently started working on one using Bootstrap 5. I am looking to dynamically add or remove the "bg-opacity" Bootstrap class from my navbar based on the viewport width. I initially attempted to achieve thi ...

How to specify in TypeScript that if one key is present, another key must also be present, without redundantly reproducing the entire structure

In my code, I have a custom type defined like this (but it's not working): type MyType = | { foo: string; } | { foo: string; barPre: string; barPost: string; } | { foo: string; quxPre: string; qu ...

Struggling with implementing Vue.js for making a task list using Bootstrap 5

I'm trying to get the hang of Vue.js. I've been working on setting up a to-do list where users can input tasks, but I'm having trouble getting the list to display correctly when I define the method. It seems like my add() function isn't ...

Stop images from constantly refreshing upon each change of state - React

Within my component, I have incorporated an image in the following way: <div className="margin-10 flex-row-center"> <span> <img src={spinner} className="spinner" /> ...

Step-by-step guide for sending information to a personalized API using Ajax on the Syncfusion Angular Scheduler

I'm currently grappling with how to send data to my API whenever a new event is created using the editor window. My approach so far involves using Ajax to fetch content, as seen in the code snippet below; const ajax: Ajax = new Ajax( "https://l ...

SSI stands for Server Side Includes, a feature that allows

I have multiple versions of the same HTML page, each with only one hidden variable that is different. This variable is crucial for tracking purposes. Now, I am exploring options to rewrite this by incorporating a HTML file with a hidden variable. Here is ...

An error occurred while parsing JSON: `Unexpected ending near "ma-sauce-launcher":"*`

After executing the command ">ng new angular-app" on Windows, I came across the following error: npm ERR! Unexpected end of JSON input while parsing near '...ma-sauce-launcher":"*' Package installation failed, please refer to the above error ...

Does the AngularJS Controller disappear when the DOM element is "deleted"?

One challenge I encountered is regarding a directive that is connected to an angularjs controller, as shown below: <my-directive id="my-unique-directive" ng-controller="MyController"></my-directive> In the controller, at a certain point, I ne ...

Adding a JSON file to an Angular app hosted on a Grunt server

I'm currently following a beginner's guide for Angular and I need to incorporate a JSON file into my project. I started off by using Yeoman to set up my application, which is running on grunt. var phonecatApp = angular.module('phonecatApp& ...

Is there a way to locate and delete an image element with a broken hyperlink?

My website is currently hosted on Wordpress, and I've noticed that there is an issue with a broken image link on my site. I'm not sure when this occurred, but it seems to only be affecting the post section of my site. https://i.sstatic.net/iarDU ...