When using Angular 10 or later, the mouseclick event will consistently trigger Angular's change detection mechanism

When I bind an event to elements on a component's HTML page, the component continues to detect changes even when the element event is fired. Despite setting the change detection mode of the component to OnPush, this behavior persists. To test this, I created a simple project with no dependencies except for the Angular core library.

Here is the code snippet:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
  title = 'angular-tour-of-heroes';


  onClick() {
    console.log("click");
  }

  value(){
    console.log("detect fired");
    return "value";
  }

}


app.component.html code

<button type="button" (click)="onClick()">button</button>
{{value()}}

The browser console output after clicking the button:

click

detect fired

After clicking the button, "detect fired" is displayed in the console without any code calling the method ChangeDetectorRef.markForCheck().

Thank you!

I expected the value() method not to be executed when I click the button unless I specifically call

changedetectionref.markForCheck()
.

Answer №1

An OnPush change detector is not only triggered by changes in component Input() references. It also activates if:

  • A component event handler is executed
  • An observable connected to the template through the async pipe emits a new 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

release a Node.js module on NPM

Being a complete beginner in creating npm packages using typescript2 and angular2, I find myself in need of creating an npm package and publishing it on our company's private repository. I've managed to generate files like d.ts and .js. But how ...

Angular2-material causing problem with scrolling in the md-content

I am attempting to create a layout where, md-toolbar remains fixed at all times Only md-content scrolls on the entire page if the content overflows. md-sidenav and its content should always remain fixed regardless of its mode ('over' or & ...

Erase Typescript Service

To remove a PostOffice from the array based on its ID, you can use a checkbox to select the desired element and then utilize its ID for the delete function. Here is an example: let postOffices = [ {postOfficeID: 15, postCode: '3006&ap ...

A guide on activating the <b-overlay> component when a child triggers an Axios request in vue.js

Is there a way to automatically activate the Bootstrap-vue overlay when any child element makes a request, such as using axios? I am looking for a solution that will trigger the overlay without manual intervention. <b-overlay> <child> ...

Setting up D3 on a Meteor Angular2 project

Currently, I am attempting to combine D3 and topojson within the context of Meteor + Angular2. import { Component } from '@angular/core'; import template from './d3map.component.html'; * import 'd3' @Component({ selector: ...

Generating a fresh instance of input value in Angular2

In the hierarchy of components, I have a grand parent component where I am passing the "selectedValue" to the parent component like so: @Component({ selector: 'grand-parent', template: '<parent [details]="selectedValue" ></par ...

Unresolved promise: Internal server issue

I encountered an exception while working on my Nativescript app. EXCEPTION: Uncaught (in promise): Server error JS: ORIGINAL STACKTRACE: JS: Error: Uncaught (in promise): Server error JS: at resolvePromise (/data/data/com.yourdomain.appname/files/app/ ...

Exploring the world of Unicode in Angular

I need to search for pokemon and retrieve all Pokémon results (with the accent included) This is my array: let games = ['The Legend of Zelda', 'Pokémon', 'Chrono Trigger'] This is how I am attempting to do it: Using HTML ...

No errors are being displayed with the React Hook Form using Zod and Material UI

Presenting my custom ProductInfoForm built using Material UI, react-hook-form with zod validations. However, I am encountering an issue: upon submitting the form, the data is displayed in the console as expected, but when intentionally triggering an error, ...

What practical applications exist for preserving JSX post-transpilation of a tsx file?

While troubleshooting another issue, I decided to delve into Typescript's documentation on JSX usage. I discovered that some options involve converting JSX while others do not. I am puzzled as to why one would need to preserve JSX in transpiled file ...

Angular - The argument provided is not compatible with the parameter

I encountered the following TypeScript errors in app.component.ts: Issue: Argument of type '(events: Event[]) => void' is not assignable to parameter of type '(value: Event[]) => void'. Description: Types of parameters 'e ...

Encountering an unexpected termination error when using Typescript, pg, Express, and Psql within a Docker container: "Error: Connection terminated unexpectedly"

I am facing an issue with connecting to my database running on a Docker container using a postgres image: docker run --name postgres-container -p 2345:2345 -e POSTGRES_PASSWORD=password123 -e POSTGRES_USER=admin -d postgres The TypeScript code I have is i ...

Developing a discriminated union by utilizing the attribute names from a different type

In my quest to create a unique generic type, I am experimenting with extracting property names and types from a given type to create a discriminated union type. Take for example: type FooBar = { foo: string; bar: number; }; This would translate t ...

Create a configuration featuring filter options similar to Notion's functionality

The objective is to create a system that can establish certain constraints, similar to the way Notion handles filter properties. https://i.sstatic.net/plctW.png System A sets up the constraints and System C evaluates them, both using Typescript. However, ...

What exactly is the concept behind the Strategy OnPush?

I am a beginner in the world of Angular2 with TypeScript. As I delve into my project, one concept that continues to elude me is the purpose of OnPush: changeDetection : ChangeDetectionStrategy.OnPush Despite my dedicated efforts in researching this top ...

Tips on creating a Jasmine unit test scenario for a function that triggers onerror of an image tag

I am facing an issue with the code below as the test case is failing //test case it('should display default image if the image link in people finder result does not exist', fakeAsync(() => { debugger component.resultsItem = M ...

Issue with Reusable Component in Angular 11- not functioning as expected

Attempting to grasp and implement the concept of reusability in Angular. I am working on creating a reusable component using <mat-card> which I intend to use across different modules' components. Currently, I have set up a framework for reusabi ...

What methods can I use to prevent the addition of new values and duplicates within angular mat-chips?

I am utilizing angular 9 mat-chips and I am seeking a way to prevent adding new values in the input field, allowing only items from the autocomplete list to be added. For instance, if 'abc' is typed, which is not in the autocomplete list, pressin ...

Issue with auto formatting quotes in IntelliJ / WebStorm is no longer functioning as expected

Currently, my TSLint configuration is set to permit the use of single quotes (') instead of double ones ("). Previously, I was able to conveniently switch all instances of " to ' in a file by using the Reformat Code shortcut CTRL + ALT ...

Troubleshooting issues with Angular Material's basic mat-autocomplete functionality

After spending more than 72 hours trying to resolve this issue, I have hit a roadblock. Oddly enough, when I create a minimal working example in stackblitz, everything functions perfectly. The problem lies within a simple mat-autocomplete embedded within ...