Dealing with the Angular 7 ExpressionChangedAfterItHasBeenCheckedError in combination with NgsScrollReveal

Utilizing ngScrollReveal triggers a re-render with every scroll event. I am invoking a function through the HTML in this manner:

<component [alternate]="toggleAlternate()">

The code for toggleAlternate() is as follows:

toggleAlternate() {
  this.alternate = !this.alternate;
  return this.alternate;
}

Unfortunately, I encounter an error during each scroll event:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'alternate: false'. Current value: 'alternate: true'.

I have attempted to resolve this issue by injecting ChangeDetectorRef and invoking detectChanges() within the toggleAlternate() method, but that did not eliminate the error. As a newcomer to Angular, I am uncertain about how to address this.

Is there a way to avoid calling the toggleAlternate() method with every render?

While the UI currently functions correctly, I aim to eradicate the console errors.

Update

My goal is to present my work experience as a timeline where each entry alternates with the preceding one.

This is where toggleAlternate() is utilized:

<app-work-ex-position *ngFor="let job of year[Object.keys(year)[0]].jobs" [job]=job [alternate]="toggleAlternate()">
</app-work-ex-position>

This is how the <app-work-ex-position /> component appears:

<app-work-ex-timeline-entry (expand)="onExpandEntry($event)" class="{{alternate ? 'alternate' : ''}}">

<app-work-ex-timeline-entry-dot class="{{isExpanded ? 'primary-circle' : 'primary-circle circle-not-expanded'}}"
                      [size]="30"
                      [isAlternate]="alternate">
</app-work-ex-timeline-entry-dot>
</app-work-ex-timeline-entry>

Depending on the returned value of alternate from the parent component, I set the appropriate CSS class.

Answer №1

It's not recommended to call a function that modifies the component state directly from the HTML. This can lead to instability in the component's state as the function will be invoked during every change detection cycle.

If you're looking to apply a CSS class alternately within the component, you should utilize the even and odd variables provided by *ngFor, as detailed in the Angular documentation here.

To achieve this, adjust your code like so:

<app-work-ex-position 
    *ngFor="let job of year[Object.keys(year)[0]].jobs; even as isEven" 
    [isAlternate]="isEven">
</app-work-ex-position>
set isAlternate(value: boolean) {
  this.alternate = value;
}

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

An iron-dropdown made of polymer featuring a trigger button made of paper-icon-button

I am facing an issue on my Angular site where I have integrated Polymer. I am trying to add a notifications section to the header, but I am struggling to make the button functional. How can I bind the click event of the button to trigger the dropdown? Thi ...

Eureka - Spring Cloud Services: Discover the Benefits

Currently, I am diving into the world of microservices with Spring and Spring Boot, looking to deploy my work onto a cloud platform. My goal is to develop an Angular 2 frontend application that interacts with my deployed microservice. Right now, I am exp ...

tips for aligning items in the center with angular flexbox

I'm attempting to create an Angular Material application using the angular flex layout as shown in this demo. Despite trying different configurations, I can't seem to get it right. My goal is to have multiple cards under a toolbar that take up ab ...

Is it necessary to ensure application readiness before proceeding with unit testing exports?

I've been facing a challenge while trying to utilize Jest for unit testing an express API that I've developed. The issue arises when the database needs to be ready before running the test, which doesn't seem to happen seamlessly. In my serve ...

Unable to pass response from httpclient post method to another custom function in Angular 4

I've implemented the addUser(newUser) function in my sign-in.service.ts file like this: addUser(newUser) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; let body = JS ...

"Exploring the method to navigate through a nested Firebase collection linked to its parent collection

I have a forum application in development where users can ask questions and receive answers, each answer having its own 'like' feature. I am trying to access the 'likes' subcollection when viewing an answer, but I am unsure of how to do ...

Executing a component method from a service class in Angular

When trying to call a component method from a service class, an error is encountered: 'ERROR TypeError: Cannot read property 'test' of undefined'. Although similar issues have been researched, the explanations mostly focus on component- ...

Tips and tricks for displaying JSON data in Angular 2.4.10

In my Angular project, I am facing an issue while trying to display specific JSON data instead of the entire JSON object. Scenario 1 : import { Component, OnInit } from '@angular/core'; import { HttpService } from 'app/http.service'; ...

There seems to be an issue with executing an imported function from a .ts file within a TSX file in NextJs, resulting

I've encountered an issue that seems to be related to using NextJs with TypeScript. For example: // /pages/index.tsx import _ from 'lodash' export const MyComponent = () => { return ( <ul> { _.map(someArray, ...

The Relationship between Field and Parameter Types in TypeScript

I am currently working on a versatile component that allows for the creation of tables based on column configurations. Each row in the table is represented by a specific data model: export interface Record { attribute1: string, attribute2: { subAt ...

Angular CLI - managing separate development and production assets

Is there a way to switch to a different set of assets when using the --prod flag with ng build? In my scenario, I have multiple projects that share a common set of assets in a designated folder. Each project's configuration in angular.json looks simi ...

When using Angular2, I have found that I am unable to extract the body data from JSONP responses. However, I have discovered that this issue

Initially, I developed the SERVER using spring-boot framework. The code for this looks like: public class App { @RequestMapping("/") @ResponseBody String home(HttpServletRequest request) { String aa=request.getParameter("callback"); System.out.pri ...

Angular API data causing an undefined error in the template

When attempting to display values in an HTML template from API data, I encountered an issue. Despite not defining all the values in the object, the data is displayed correctly. However, an error appears in the console: TypeError: Cannot read property &ap ...

The art of linking Observables on the fly in rxjs and angular

In my current project, I am facing a challenge where multiple events can be triggered from an object. These events are handled by a component and then sent to a REST API. The issue arises when I need to ensure that calls to the REST API for a specific reso ...

Ensuring the validation of JSON schemas with dynamically generated keys using Typescript

I have a directory called 'schemas' that holds various JSON files containing different schemas. For instance, /schemas/banana-schema.json { "$schema": "http://json-schema.org/draft-06/schema", "type": "object", "properties": { "banan ...

How can I create a box-shaped outline using Three.js?

As someone new to threejs, I have been trying to figure out how to render a transparent box around a symbol in my canvas. The box should only display a border and the width of this border should be customizable. Currently, I am using wireframe to create a ...

What is the process for generating an injected and a const object instance?

How can an instance of class A obtain a dependency on an instance of class O, while remaining a singleton for others? @injectable() class O{} // A must be single instance! @injectable() class A{ constructor(o: O){ console.log( 'is A inst ...

implementing a directive in an Angular 2 component

Just finished putting together a basic project with angular 2. Ran into an issue when attempting to include a directive component in the app.component - getting a red underline under the 'directives' property. Anyone out there know what's go ...

What steps should I take to convert the lazyload module in routes into a regular module?

Software Version: ng version: @angular/cli: 1.0.0-rc.1 node: 6.10.2 os: win32 x64 @angular/common: 4.1.1 @angular/compiler: 4.1.1 @angular/compiler-cli: 4.1.1 @angular/core: 4.1.1 @angular/forms: 4.1.1 @angular/http: 4.1.1 @angular/platform-browser: 4.1.1 ...

What is the reasoning behind defaultValue possessing the type of any in TextField Material UI?

According to the Material UI guidelines, the component TextField specifies that its defaultValue property accepts the type any. I decided to experiment with this a bit and found that in practice, defaultValue actually supports multiple types. You can see ...