1

I have a scenario where I have @Input-less OnPush component in Angular. If I call markForCheck(), the view binding in my component's template will be checked?

I mean, my component is OnPush and markForCheck() marks all ancestors to be checked and because my component has no @Input, what will be the behaviour of Angular here? Will Angular skip checking component's view bindings or will it always check?

0

1 Answer 1

1

As you can see from the source code example from ChangeDetectorRef. The view shows the value numberOfTicks which is updated when markForCheck() is called. Notice that the component has no @Input() bindings.

 @Component({
    selector: 'cmp',
    changeDetection: ChangeDetectionStrategy.OnPush,
    template: `Number of ticks: {{numberOfTicks}}`
  })
  class Cmp {
    numberOfTicks = 0;

    constructor(private ref: ChangeDetectorRef) {
      setInterval(() => {
        this.numberOfTicks++;
        // the following is required, otherwise the view will not be updated
        this.ref.markForCheck();
      }, 1000);
    }
  }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for commenting and explaining it with an appropriate example. I have just a small question. Imagine, Cmp has some inputs which haven't changed and same code gets called. Will markForCheck() still checks Cmp in that scenario for changes or it will just skip it because it has ChangeDetection set to OnPush and that inputs haven't changed?
@ImranLatif markForCheck will set a flag on the view that it's dirty no matter what the inputs are. detectChanges will execute change detection immediately. Both methods update the HTML of the template. ngOnChanged for the interface OnChanges is called only when @Input() has changed. I think this might be your confusion. There is a difference between @Input() bindings and the view. The view is what renders the template. The template gets rendered when it's marked dirty. markForCheck manually sets the dirty flag. ON_PUSH sets it only when inputs changed.
Thanks for the awesome explanation @cgTag.

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.