S
S
sequelsur2021-09-13 00:09:42
Angular
sequelsur, 2021-09-13 00:09:42

Why does Angular only update a variable in the DOM once?

Why does Angular only update a variable in the DOM once?
whether it's a service or a component, I'm trying to hide the element via *ngIf boolean variable, but angular only sees when the variable changes the first time, it doesn't see it the second time. BUT if to make console.log that the variable all the same changes.
I would do ChangeDetectorRef, but what if the variable is stored in the service, and I need it to change in all DOM components where it is used.
Sorry if I phrased it wrong

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Shcherbina, 2021-09-13
@Denis_maker

Here is an example of how to subscribe to a variable in a service.
https://stackoverflow.com/a/43161506
Without such an event subscription in the service, the data is loaded once at a time.

A
Anton Shvets, 2021-09-13
@Xuxicheta

1. Store all time-varying entities in an Observable
2. An Observable that needs to be changed outside is called a Subject. Its varieties that can remember values ​​are called ReplaySubject (initially empty) and BehaviorSubject (initially must be initialized).
3. Take links to data from the service to the component.
4. Don't subscribe to them, just insert them into the template via asyncPipe
Example.
In service

private flagSource = new BehaviorSubject(false);
public flag: Observable<boolean> = this.flagSource;

setFlag(value: boolean) {
   this.flagSource .next(value);
}

in the component in the asyncPipe template, it watches the observable and forces the component to participate in change detection
flag = this.myService.flag;
<div *ngIf="flag | async">

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question