Search code examples
angulartypescriptsession-variables

Get session variable directly in component HTML within Angular application?


Is there a way to get and display the the value of session variable directly in component HTML without assigning a local variable with the value of session variable ?

Something like:

<span>{{sessionStorage.getItem('name')}}</span>

Solution

  • As mentioned in the Angular documentation, the expression context in the template is the component instance. Since sessionStorage is a member of the window object, you cannot refer to it directly in the template:

    Template expressions cannot refer to anything in the global namespace, except undefined. They can't refer to window or document.


    You can make sessionStorage available in the template by assigning it to a public property of the component class:

    export class MyComponent {
      public sessionStorage = sessionStorage;
    }
    

    and refer to that property in the template:

    <span>{{sessionStorage.getItem('name')}}</span>
    

    See this stackblitz for a demo.