Home > OS >  Why getter triggers sometimes in template?
Why getter triggers sometimes in template?

Time:10-28

There is a component in which the children are activated by the ngIf condition.

Wrote a getter to check how many times it jerks:

{{test}}
<app-comp1 * ngIf = "one"> </app-comp1>
<app-comp2 * ngIf = "two"> </app-comp2>

Getter:

   get test () {
     console.log ('1')
     return '1'
   }

When switching tabs - changing one, two variables - the getter is called 4 times.

What could be the reason? The component has changeDetection: ChangeDetectionStrategy.OnPush

CodePudding user response:

In OnPush there are 3 ways change detection gets triggered:

  • An @Input of your component change (compared with ===)
  • An event you subscribed to with () in template or @HostListener in code happens
  • Change detection is manually triggered (i.e with ChangeDetectorRef)

So in your case even if component is under onPush strategy, but event occurs in that component, it will be checked for changes

  • Related