1

I am using HostListener 'window:scroll' event in my component as shown in this demo. While I scroll the components re render itself. In console I am printing sample text which is inside component that should run only one time.

Need help what I am doing wrong here.

1
  • 1
    thats how change detection works. Commented Aug 28, 2019 at 10:18

1 Answer 1

3

The rendering is triggered by the default change detection strategy.

Basically the HeaderComponent is triggered by HostListener to check the state of the component, which then propagates to the child components.

The FirstComponent's change detector is by default ChangeDetectionStrategy.Default, because of which it re-checks the state each time change detection is triggered. The other option would be to set ChangeDetectionStrategy to OnPush.

This would make the component to check for changes only whenever the actual state is changed. For example when Input() or Output() is changed or when the template event is raised ((click)="onClick()" in HTML for example).

I would highly recommend to read more about the change detection mechanism in Angular in more details.

Here's the working solution:

import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-first',
  template: `{{abc()}}`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FirstComponent  {
  constructor() {}
  abc(){
    console.log('first component')
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great explanation. Every day learning and never finish. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.