How to Implement Angular ngStyle with ChangeDetectionStrategy.OnPush?

Check out this StackBlitz demonstration that demonstrates how ngStyle is being used to style the h1 element in the following way:

<h1 [ngStyle]="{'background-color': backgroundColor}"

The component named HelloComponent employs the OnPush change detection strategy as shown below:

@Component({
  selector: 'hello',
  template: `<h1 [ngStyle]="{'background-color': backgroundColor}">Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
})

After attempting to update the background color to yellow in the ngAfterViewInit() method, it appears that the view does not reflect the change and remains blue.

What steps can be taken to trigger change detection so that the style updates accordingly?

I experimented with using this.cdr.markForCheck() to see if I could manually trigger it.

Answer №1

According to the console on your StackBlitz, an error occurred:

ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'blue'. Current value: 'yellow;'.. 

It seems like a simple typo. Please update

this.backgroundColor = 'yellow;'

to

this.backgroundColor = 'yellow';

(move the semicolon outside the string 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

There is no corresponding version available for [email protected] in Angular 6

After cloning a project from git, I attempted to run npm install. However, an error message popped up, as shown in the following link: https://i.stack.imgur.com/pqYbK.png Can someone please explain why this is happening and how I can resolve it? Any help ...

Encountered an error: Object(...) does not conform to function standards in the handleChange method

When using JavaScript, everything works fine. However, when trying to implement TypeScript with the handleChange function, an error is consistently thrown whenever something is typed into the entries. The error message reads: "TypeError not captured: Objec ...

Divergent find function behavior in jQuery when applied to div or tbody

I've encountered an issue while using the jQuery find selector by Id with a div and tbody. Let me simplify my problem for better understanding. HTML <div id='iamdiv'>HELLO</div> <table> <tbody id='iamtbody' ...

Is there a way for me to detect if the user has manipulated the CSS or JavaScript in order to alter the look of my website?

Is there a way to determine if someone is utilizing script or CSS extension tools? For instance, if they have adjusted alignments, applied display: none; to multiple elements, or utilized jQuery's .hasClass to manipulate divs. ...

Header contains problem with cross-domain access in $http

Sending a request through Angularjs $http with JSON data to my REST service requires setting headers once the response is returned. The necessary headers are added as follows, Response.ok() .entity(emp) .headers.add("Access-Control-Allow-Origin", "*") .he ...

Aligning columns vertically in the Bootstrap grid

So you've got a layout with two columns using Twitter Bootstrap, and you want to make sure specific rows are vertically aligned: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha/css/bootstrap.min.css"/> < ...

Data service with a variety of return types

I have developed a versatile data service structure that has the following implementation: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable& ...

What is the best way to incorporate data from my Express server into my HTML table?

I am seeking a way to dynamically add new rows to a table in my HTML file by fetching data from server.js using Express. I am aware that I can use double curly braces "{{example}}" in the HTML file to insert values from the server file using "res.render(vi ...

Remove the list by conducting a comparison analysis

<html> <head> <title> Manipulating List Items Using JavaScript </title> <script type="text/javascript"> function appendNewNode(){ if(!document.getElementById) return; var newlisttext = document.changeform.newlist.val ...

Tips for importing libraries in a web-worker with TypeScript

In order to load extension-like code in a web worker and import external libraries, I am facing an issue with the typescript compiler not generating valid code for the web worker. My current workaround involves constructing the Worker with type module so ...

The search results fail to show the required information

I am trying to retrieve data from an API based on a search query. When the user enters the name of the film they are looking for and hits enter to submit the form, the matching films should be displayed on the screen. However, my console is showing errors ...

I can't understand why my server is displaying an error on the browser stating "This site can't be reached ERR_UNSAFE_PORT" while it is functioning flawlessly on the terminal

I have created an index.html file, along with index.js and server.js. In the server.js file, I have included the following code: const express = require("express"); const path = require("path" ); const app = express(); app.use(" ...

What are the steps for implementing videojs vr in a Vue.js project?

After installing the videojs vr with npm install --save videojs-vr, I attempted to use it in my project: https://i.stack.imgur.com/lSOqF.png However, I encountered this error message: https://i.stack.imgur.com/QSe1g.png Any assistance would be greatly ...

Converting CSS colors from RGBA to hexadecimal format: A step-by-step guide

Within my selenium code, I am faced with the challenge of verifying that the background color code is #192856. However, when obtaining the CSS property of the element, it returns the color in rgba format. How can I retrieve the values in hex format? quick ...

What is the best way to incorporate markers into my d3 line chart that includes two separate datasets?

In my JavaScript code, I'm creating a line chart for two datasets using the d3 library with Vue framework integration. Within the HTML code, there are buttons that trigger the updateData function to display the line charts for the respective datasets ...

Navigation bar with horizontal layout

I have the following HTML: <div id="filter-menu"> <div class="filter-item home selected"></div> <div class="filter-item animals"></div> <div class="filter-item ancient"></div> <div class="filte ...

Using AJAX to handle 404 errors in Slim PHP

When I attempt to retrieve data using AJAX in my Slim PHP application, I am encountering a 404 (Not found) error in the console. The specific error message is as follows: http://localhost:8888/Project/mods/public/edit-mod/ajax/get-categories?gameID=1 404 ...

The issue with updating values in the jQuery UI datepicker persists

When using the jquery datepicker ui, you may notice that the value attributes of the associated html fields do not update immediately. For example: http://jsfiddle.net/4tXP4/ Check out this link for more details: http://jqueryui.com/demos/datepicker/al ...

NestJS wonderful imports - Nest unable to resolve dependencies

Recently, I came across a tutorial at Following the NestJS part of the tutorial, I encountered an error despite having code that seemed identical to the one in the tutorial. [Nest] 94625 - 10/01/2024, 11:43:53 AM ERROR [ExceptionHandler] Nest can' ...

Working with Angular 4 and Typescript: Transforming JSON data with json2typescript key mapping

Apologies for the confusion in my previous explanation. Let me clarify my question: In my Angular 4 application, I am using json2typescript to handle JSON to object conversion. However, I am facing an issue where the class structure I have defined does no ...