0

Suppose we have a getter defined like this:

  get sku() {
    return this.form.get('sku').value
  }

And we use it like this:

    <mat-hint *ngIf="!sku">Example sku123</mat-hint>

Is there a better way of doing this from an Angular Change detection performance perspective?

We could use an Observable. Something like this I think (Roughing this out):

sku$ = this.form.get('sku').valueChanges().pipe(untilDestroyed(this))
<mat-hint *ngIf="!(sku|async)">Example sku123</mat-hint>

Is one better than the other?

IIUC the getter will be called whenever there is change detection, but if we use ChangeDetectionStrategy.OnPush with the Observable then will only receive notifications when the form updates?

2

2 Answers 2

1

using ChangeDetectionStrategy.OnPush will not apply the change to your sku in the view *ngIf because automatic change detection is deactivated now. Only the event will be triggered without changing the view. Therefore, you will have to explicitly invoke it using,


constructor(private cdRef: ChangeDetectorRef) {}

this.form.valueChanges
    .subscribe(() => {
      this.cdRef.markForCheck();
    });
  }
<mat-hint *ngIf="!sku">Example sku123</mat-hint>

Note: Performance will be increased by using ChangeDetectionStrategy.OnPush as it only runs the cycle once. But will get complicated when it comes to reactive forms. And also all the child components inside the parent component using ChangeDetectionStrategy.OnPush will be inherited and you will have to invoke them manually if needed.

0

Getter is fine for the performance, except if the function is expensive as it will be called at each cycle. In this case, a pipe is preferred as the result is cached.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.