cezn
cezn

Reputation: 3055

Angular change detection triggers after every handler?

Let say I have two click handlers attached to dom inside template:

<div (click)="handleClick()">
  <p (click)="handleClick()">
    Start editing to see some magic happen :)
  </p>
</div>

and following in ts file:

export class AppComponent implements DoCheck {
  handleClick(){
    console.log('AppComponent: handle click');
  }

  ngDoCheck(){
    console.log('AppComponent: ngDoCheck');
  }
}

Now, if someone clicks on p element, change detection is fired after every click handler (ngDoCheck executed twice). When I add more handlers, number of change detection phases increase accordingly.

Here's example: https://stackblitz.com/edit/angular-czdzzk

In this trivial example it's harmless, but I'm currently working on a bigger application, where there are tens of components on the page, and multiple handlers attached (mainly to window.document by external libraries). In this case, after clicking anywhere on the page, components are checked many times.

Is there a way to execute change detection once after all handlers are executed? Or is it implemented this way for some reason?

Upvotes: 0

Views: 1031

Answers (1)

Baruch
Baruch

Reputation: 2428

Use ChangeDetectionStrategy.onPush Angular docs. You should always use onPush

@Component({
  selector: 'selector'
  changeDetection: ChangeDetectionStrategy.onPush,
  //...
})
export default MyComponent {
  //...
}

Upvotes: 1

Related Questions