3

I have problem with using *ngIf with observable variables. The thing is that when I hide element with *ngIf, and show it again, values won't load so:

        <div *ngIf="showDiv">
             {{ someObservable$ | async }}
        </div>

Basically when showDiv is set to true at the first place, the someObservable loads, but when I set it to false and then again to true , value won't load. What's wrong?

Regards

1 Answer 1

5

UPDATE:

Thanks to j2L4e, for his hint!

BehaviorSubject is the key!

See this plunker:

https://plnkr.co/edit/whkrQk3tHCJCvvi6rlaE?p=info

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

import { Subject, BehaviorSubject } 'rxjs/Rx';
//import { Observable, Subject } from 'rxjs';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 (click)="showMe = !showMe">Hello {{name}}</h2>
      <br />

      <div *ngIf="showMe">
        sbj1: {{  _subj1 | async  }}
      </div>

      <div *ngIf="showMe">
        obs1: {{  _obs1 | async  }}
      </div>

      <div *ngIf="showMe">
        obs2: {{  _obs2 | async  }}
      </div>
    </div>
  `,
})
export class App {

  private showMe = false;

  private _subj1 = new BehaviorSubject<string>();
  private _subj2 = new Subject<string>();
  private _obs1 = this._subj1.asObservable();
  private _obs2 = this._subj2.asObservable();

  constructor() {
    this.name = 'Angular2'

    this._subj1.next('in constructor');
  }

  ngAfterViewInit() {
    this._subj2.next('after view init..');
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}
Sign up to request clarification or add additional context in comments.

1 Comment

BehaviorSubject is what you'd need here. It caches a single value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.