Filip Witkowski
Filip Witkowski

Reputation: 965

Angular - best way (for performance) to update view based on service

I have uiSettings service, which based on user data will control parts of templates (in different places).

Currently I use this service directly from template. for example:

<li *ngIf="uiService.demoButton()">
      <button [routerLink]="/demo" class="secondary">Demo</button>
</li>

In Service:

demoButton():boolean {
    return this.demoButtonAvailable;
  }

Above property is updated only when something changes for the user (login, logout, update..), but template calls the uiService.demoButton() every second or so.

I believe there is a better way (for performance) to do it. If I use observable, would I observe this value, or wait for event fired after the needed variable is updated?

Upvotes: 0

Views: 559

Answers (3)

Ganesh
Ganesh

Reputation: 6016

You can just simply use the service variable demoButtonAvailable like below,

...

<li *ngIf="uiService.demoButtonAvailable">
      <button [routerLink]="/demo" class="secondary">Demo</button>
</li>

...

If I use observable, would I observe this value, or wait for event fired after the needed variable is updated?

You don't need to use Observable with event for a simple Boolean. YES, it will trigger every time because it's method call in the view ( which is not recommended), but you can use service boolean variable unless you want another component variable with service data.

Upvotes: 0

KamLar
KamLar

Reputation: 428

You can use BehaviorSubject and async pipe to notify when something change. You can then use changeDetectionStrategy: ChangeDetection.onPush or detach changeDetectorRef and detect changes manually.

Upvotes: 1

Timothy
Timothy

Reputation: 3593

ngIf condition runs on every change detection, you need to wrap it with some conditional variable. For example

<li *ngIf="demoButtonAvailable">
      <button (click)="uiService.demoButton()" class="secondary">Demo</button>
</li>

Upvotes: 0

Related Questions