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

Simultaneously accessing multiple APIs

I am currently facing an issue with calling two API requests sequentially, which is causing unnecessary delays. Can someone please advise me on how to call both APIs simultaneously in order to save time? this.data = await this.processService.workflowAPI1(& ...

In order to work with the optionSelectionChanges property of the MdSelect directive in Angular Material2, it

Within my application, there is a Material2 select dropdown widget containing several options. app.component.html <md-select placeholder="Choose an option" [(ngModel)]="myOption" (optionSelectionChanges)="setOptionValue(myOption)"> &l ...

The element 'fontFamily' is not recognized within the 'ThemeOptions' type in MUI theming

I'm diving into the world of React and MUI by building my own dashboard from scratch. Let's take a look at my App.tsx file: import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; i ...

I am facing an issue with the Angular2 Modal Form where it only displays the data but does

Hey there, I recently started diving into Angular and I'm loving the learning process. Currently, I've managed to successfully load a form into my Modal when clicking on "viewDetails". However, as soon as I modify the Form from <form ngNoFo ...

Is dynamic routing in Angular 8 only functional when utilizing RouterLink?

While working on dynamic routing in Angular, I ran into a strange issue. Dynamic routes only seem to be functional when accessed through a RouterLink, but the app crashes whenever I try to directly enter the URL in the browser. (The console error message ...

I am looking to present a nested array within an array in a tabular format

This is the structure of my database: [{ "firstName": "Shaun", "salary": [ { "id":1, "rate": 250, }, { "id":2, "rate": 290, } ] },{ "firstName": "Julian", "salary": [ { "id":1, "rate": 750, ...

Executing secure journey within TypeScript

Just came across an enlightening article on Medium by Gidi Meir Morris titled Utilizing ES6's Proxy for secure Object property access. The concept is intriguing and I decided to implement it in my Typescript project for handling optional nested object ...

What steps should be taken to find a particular route when a user logs in for the first time?

I am currently working on an application using Angular 2+, Node.js, and Express.js that includes registration and login authentication functionality. How can I direct first-time users to a specific route upon login, but for all subsequent logins have them ...

Encountering an error stating "Argument of type 'X' is not assignable to parameter of type 'X' in the NextApiResponse within NextJS."

Here is the code snippet I am working with: type Data = { id: string; name: string; description: string; price: number; }; const FetchMeals = async (req: NextApiRequest, res: NextApiResponse<Data>) => { const response = await fetch( ...

Exploring the Power of PrimeNG and Observables in Angular 4 with RxJS

After configuring my Angular 4 project with a service like this: const usersURL = 'http://my.super.url.php'; @Injectable() export class UserService { users: Observable<User[]> constructor (public http:Http) let tick$ = Observ ...

Indicate the type of content returned by a Controller

I'm dealing with a metrics.controller.ts file that looks like this: import { Controller, Get } from '@nestjs/common'; import { ApiOperation, ApiResponse, ApiUseTags, ApiModelProperty } from '@nestjs/swagger'; import { PrometheusSe ...

Error message: The rootLocator function in NativeScript RadListView is not able to be

I encountered a strange error when using RadListView in the following code: <RadListView [items]="dataItems"> <ng-template tkListItemTemplate let-item="item"> <StackLayout orientation="vertical"> ...

Setting a default value for the dropdown in Angular is essential for ensuring a smooth

<select [(ngModel)]="detail.State" (ngModelChange) ="onStateChange()" class="form-control"> <option [ngValue]="null" disabled selected>Select State</option> <option * ...

Can an enum be declared in Typescript without specifying a type explicitly?

Within an interface, I have a group of 10+ (optional) members, most of which have a specific set of potential values. To streamline this, I would like to utilize enums. However, creating separate enum types for each member (which are only used once and hav ...

Utilizing regular expressions to search through a .md file in JavaScript/TS and returning null

I am currently using fs in JavaScript to read through a changelog.MD file. Here is the code snippet: const readFile = async (fileName: string) => { return promisify(fs.readFile)(filePath, 'utf8'); } Now I am reading my .md file with this fu ...

The video in the TypeScript code within the Owl Carousel is not displaying properly - only the sound is playing. The video screen remains stationary

I recently updated my query. I am facing an issue while trying to play a video in Owl Carousal with a button click. The video plays sporadically, and most of the time it doesn't work properly. When playing without the carousel, a single video works fi ...

Is it necessary for me to set up @types/node? It appears that VSCode comes with it pre-installed

Many individuals have been adding @types/node to their development dependencies. Yet, if you were to open a blank folder in VSCode and create an empty JavaScript file, then input: const fs = require('fs'); // <= hover it and the type display ...

Error message in Angular 2 RC-4: "Type 'FormGroup' is not compatible with type 'typeof FormGroup'"

I'm currently facing an issue with Angular 2 forms. I have successfully implemented a few forms in my project, but when trying to add this one, I encounter an error from my Angular CLI: Type 'FormGroup' is not assignable to type 'typeo ...

Guide to Implementing Dependency Injection in Angular 2

When working with Angular Components written in TypeScript, it is possible to declare a class member (variable) as a parameter of the constructor. I am curious about the reason for doing so. To clarify, take a look at the examples below. Both achieve the ...

Unable to access material datepicker by its element id within ngAfterViewInit function

Upon component loading, I am attempting to open the material DatePicker using its element ID (#). However, when I use ngAfterViewInit, it consistently returns an error stating 'Cannot use 'open' on undefined'. Interestingly, the DatePic ...