Search code examples
javascriptangularangular-ng-ifsession-storage

Changing session storage value to undefined should affect ngIf without clicking twice


StackBlitz

When I click on button(which should make session stored variable undefined so that in other component ngIf should become false and div don't show anymore) it doesn't work first time. But when I click again it works and that div becomes hidden.

Here is my approach.

First component(This component shows first and i click on button first and then it shows second component):

//TS part
@SessionStorage() count: any;

onClick(){
this.count = "Any value";
}

<!-- HTML part-->
<button *ngIf="!count" (click)="onClick()">Click</button>

Second component:

//TS part
@SessionStorage() count: any;

onClick(){
this.count = undefined;
}

<!-- HTML part-->
<button *ngIf="count" (click)="onClick()">Click</button>

In second component I've to click twice to go to first component. I don't know where the problem is.


Solution

  • This is happening because in the second component count is undefined initially, and then once you click, it set its value to undefined, causing no change.

    If so, make sure you initialize its value with the current count:

    constructor(private sessionStorageService: SessionStorageService) {
      this.count = this.sessionStorageService.get('count');
    }
    

    Here's a demo: https://stackblitz.com/edit/angular-puzknw?file=src/app/two/two.component.ts

    This should do the trick but you should probably use a service for this, and inject it to each component.