Home > Software engineering >  angular 10 . mouseclick event always continuously fire the angular detect changes
angular 10 . mouseclick event always continuously fire the angular detect changes

Time:12-02

I binding any event on a elements in component html page, the component continuously detect changes when the element event fired .although i had set the component detect change mode be OnPush.I try build a simple project and no dependency except the angular core library.

the code :

@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()}}


browser console output when i clicked the button:
click
detect fired

when i clicked the button and output 'detect fired' even there no any code call the method :ChangeDetectorRef.markForCheck()

thank!

i thought the value() method shouldn't be executed when i click the button until i excute changedetectionref.markForCheck()

CodePudding user response:

OnPush change detector gets triggered in a couple of other situations other than changes in component Input() references, it also gets triggered for:

  • if a component event handler gets triggered
  • if an observable linked to the template via the async pipe emits a new value

https://blog.angular-university.io/onpush-change-detection-how-it-works/

  • Related