How to update the DOM if the value from an Observable is updated

48 Views Asked by At

I want to update the DOM whenever the value of the observable changes, regardless of whether the value is true or false. Here is my solution, but it's not very clear, and it's bad for performance.

<div *ngIf="isDebugMode$ | async as isDebugMode">
  <component-a>DOM Updated</component-a>
</div>

<div *ngIf="(isDebugMode$ | async) === false">
  <component-a>DOM Updated</component-a>
</div>

The expectation is to write the code block just once, avoiding the need to write it twice.

2

There are 2 best solutions below

0
Mathéüs On

I guess you're searching to update the data in real-time... Or maybe juste want to switch the component called with a boolean ?

First case :

You want to create au global variable in your component ts file and when your component is finaly built, update it with the new value in continue during the lifecycle of your component (and subscription on your observable).

It means that you create and start (by subscribing to it) an Observable. It will asynchronously fil your variable in parallel of your component lifecycle on a specific interval of time.

Unless you build a REST & Websocket structure for your project that will allow your server to communicate directly to the client connected, you have to use a recursive method from your front (in my example "interval") to reproduce the process on time (it could be very fast or slow depending on when you want to update the value).

It's an efficient way because it free your structure to duplicate lines and calls and let your typescript do the link stuff.

By the way you can check Angular's templates (<ng-template #myTemplate></ ng-template>) to re-use some structure and optimize maintainability, and Angular's binding ways.

Second case:

Decompose your application into modules and make every component standalone. Change the way you built your app-routing.module.ts and the app.modules to allow the calling method by using ... In this case you'll be able to switch component by just an interaction into the Typescript file.

I let you search for details, because if I'm out of the point I'm saving my time, ahah !

Hope I answered :)

Have a great day !

0
RG3 On

While I agree that the two solutions in the above post are better, there is a third option that I've used in certain scenarios:

You could pass in isDebugMode$ | async to each component and have the individual components handle the spacing and hide show internally. We follow a container/component pattern in our applications where the containers are only responsible for passing in the async items and the components always update when the async variables change.