Search code examples
htmlangulartypescriptreduxstore

ngif stays false, even though its value is right


My code looks like this:

component.ts

export class ViewScaleComponent implements OnInit {
    private range$: Observable<number>;
    constructor(private store: Store<AppState>) {}

    ngOnInit() {
        this.range$ = this.store.select(x => x.view.range);
    }
}

component.html:

<div *ngIf="(range$ | async)">
  here {{ range$ | async }}
</div>

The div remains commented in the DOM, an Angular Ghost.

If I remove ngif, the div appears, but the data interpolation fetches nothing (only here and the following whitespace appears).

If in ngOnInit() I do:

this.range$ = this.store.select(x => x.view.range).do(x => console.log(x));
console.log("on init " + this.range$);

then I get:

on init [object Object]
undefined
21

where the last two console logs come from the same line (do()). I wonder whether the first undefined is the reason for not displaying the di.

It's worth noting that sometimes it works(I see the div and the values ofrange$ are being updated as expected).

Any ideas?

PS: I read angular 2 ngIf with observable?, but the observable and async combination look pretty similar to mine.


Solution

  • You dont need the ngIf for this just put {{ range$ | async}}

    Update

    range:any ;
    ngOnInit() {
        this.store.select(x => x.view.range).subscribe(x => this.range = x);
    }
    

    Template

    <div *ngif="range">
      here {{ range }}
    </div>