# UI state

> UI state, app state or domain data are big terms, and we do not want to implement our own state management. For client side state management we recommend Flux / Redux / NgRx based state management frameworks like [NgRx](<https://ngrx.io>).

To separate and define these terms we use the definitions from [Redux](<https://redux.js.org/usage/structuring-reducers/basic-reducer-structure#basic-state-shape>).

- *Domain* data: data that the application needs to show, use, or modify (such as "all the Todos retrieved from the server")
- *App state*: data that is specific to the application's behavior (such as "Todo \#5 is currently selected", or "there is a request in progress to fetch Todos")
- *UI state*: data that represents how the UI is currently displayed (such as "The EditTodo modal dialog is currently open")

However, we provide a lightweight UI state service to persist some UI states, which many users like to keep through reloading the web page. The supported components are

- [Vertical Navigation](<https://element.siemens.io/components/layout-navigation/vertical-navigation/>)
- [Split](<https://element.siemens.io/components/layout-navigation/split/>)
- [List-Details](<https://element.siemens.io/components/layout-navigation/list-details/>)

Expanded and split size states are persisted in e.g. the `localStorage` of the browser and re-applied on reload.

#### Example

##### Vertical Navigation

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { Component, inject, OnInit } from '@angular/core';
import { ActivatedRoute, Router, RouterLink, RouterOutlet } from '@angular/router';
import {
  SiApplicationHeaderComponent,
  SiHeaderBrandDirective,
  SiHeaderLogoDirective
} from '@siemens/element-ng/application-header';
import { NavbarVerticalItem, SiNavbarVerticalComponent } from '@siemens/element-ng/navbar-vertical';
import { LOG_EVENT } from '@siemens/live-preview';

@Component({
  selector: 'app-sample',
  imports: [
    SiNavbarVerticalComponent,
    SiApplicationHeaderComponent,
    SiHeaderBrandDirective,
    RouterLink,
    RouterOutlet,
    SiHeaderLogoDirective
  ],
  templateUrl: './si-navbar-vertical.html'
})
export class SampleComponent implements OnInit {
  menuItems: NavbarVerticalItem[] = [
    {
      type: 'router-link',
      label: 'Home',
      id: 'home',
      icon: 'element-home',
      routerLink: 'home'
    },
    { type: 'header', label: 'Modules' },
    {
      type: 'router-link',
      label: 'Energy & sustainability',
      icon: 'element-trend',
      routerLink: 'energy'
    },
    {
      type: 'group',
      label: 'User management',
      id: 'user-management',
      icon: 'element-user-group',
      children: [
        {
          type: 'router-link',
          label: 'Sub item',
          routerLink: 'subItem'
        },
        { type: 'router-link', label: 'Sub item 2', routerLink: 'subItem2' },
        { type: 'router-link', label: 'Sub item 3', routerLink: 'subItem3' }
      ]
    },
    {
      type: 'router-link',
      label: 'Test coverage',
      icon: 'element-diagnostic',
      routerLink: 'coverage'
    },
    { type: 'divider' },
    {
      type: 'group',
      label: 'Documentation',
      id: 'documentation',
      icon: 'element-document',
      children: [
        { type: 'router-link', label: 'Sub item 4', routerLink: 'subItem4' },
        { type: 'router-link', label: 'Sub item 5', routerLink: 'subItem5' },
        { type: 'router-link', label: 'Sub item 6', routerLink: 'subItem6' }
      ]
    },
    {
      // AVOID USING `type: 'action'`.
      // Actions inside the navbar are an indication for a code smell.
      // Use `type: 'router-link'` instead whenever possible.
      type: 'action',
      label: 'Action',
      icon: 'element-warning',
      active: false,
      action: () => this.logEvent('Callback for action called')
    }
  ];

  private activeRoute = inject(ActivatedRoute);
  private router = inject(Router);
  logEvent = inject(LOG_EVENT);

  ngOnInit(): void {
    this.router.navigate(['home'], { relativeTo: this.activeRoute });
  }
}
```

Template:

```html
<div class="has-navbar-fixed-top">
  <si-application-header>
    <si-header-brand>
      <a routerLink="/" siHeaderLogo></a>
      <h1 class="application-name">Navbar Vertical Example</h1>
    </si-header-brand>
  </si-application-header>

  <si-navbar-vertical
    stateId="navbar-vertical-with-icons"
    navbarCollapseButtonText="collapse"
    navbarExpandButtonText="expand"
    searchPlaceholder="Search..."
    [items]="menuItems"
    [searchable]="true"
  >
    <div class="si-layout-main-padding">
      <div class="si-layout-header">
        <h2 class="si-layout-title si-layout-top-element">Here is a title</h2>
      </div>
      <router-outlet />
    </div>
  </si-navbar-vertical>
</div>
```

##### Split

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { Component, inject } from '@angular/core';
import { PartState, SiSplitComponent, SiSplitPartComponent } from '@siemens/element-ng/split';
import { LOG_EVENT } from '@siemens/live-preview';

@Component({
  selector: 'app-sample',
  imports: [SiSplitComponent, SiSplitPartComponent],
  templateUrl: './si-split-mixed.html'
})
export class SampleComponent {
  logEvent = inject(LOG_EVENT);

  format(name: string, state: PartState): any {
    return Object.assign({ name }, state);
  }
}
```

Template:

```html
<si-split orientation="horizontal" stateId="split-mixed" style="height: 300px">
  <si-split-part
    heading="Filters"
    stateId="filters"
    collapsible="to-start"
    class="background-1"
    size="200"
    unit="px"
    [actions]="[
      { iconClass: 'element-edit', click: logEvent, tooltip: 'edit' },
      { iconClass: 'element-delete', click: logEvent, tooltip: 'delete' }
    ]"
    (stateChange)="logEvent(format('left', $event))"
  >
    <p class="p-4 text-secondary">Split Part #1</p>
  </si-split-part>

  <si-split-part heading="Employees" stateId="employees" class="background-1" size="1" unit="fr">
    <si-split orientation="vertical" stateId="vertical-split">
      <si-split-part
        stateId="middle-top"
        class="background-1"
        size="100"
        unit="px"
        [showHeader]="false"
        (stateChange)="logEvent(format('middle', $event))"
      >
        <p class="p-4 text-secondary">Split Part #2.1</p>
      </si-split-part>
      <si-split-part
        stateId="middle-bottom"
        class="background-1"
        size="1"
        unit="fr"
        [showHeader]="false"
      >
        <p class="p-4 text-secondary">Split Part #2.2</p>
      </si-split-part>
    </si-split>
  </si-split-part>

  <si-split-part
    heading="Details"
    stateId="details"
    collapsible="to-end"
    class="background-1"
    size="200"
    unit="px"
    (stateChange)="logEvent(format('right', $event))"
  >
    <p class="p-4 text-secondary">Split Part #3</p>
  </si-split-part>
</si-split>
```

##### List-Details

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { CdkMenuTrigger } from '@angular/cdk/menu';
import { CommonModule } from '@angular/common';
import { ChangeDetectorRef, Component, inject } from '@angular/core';
import { SI_DATATABLE_CONFIG, SiDatatableModule } from '@siemens/element-ng/datatable';
import { SiEmptyStateModule } from '@siemens/element-ng/empty-state';
import { Filter, SiFilterBarComponent } from '@siemens/element-ng/filter-bar';
import { SiIconComponent } from '@siemens/element-ng/icon';
import {
  SiDetailsPaneBodyComponent,
  SiDetailsPaneComponent,
  SiDetailsPaneFooterComponent,
  SiDetailsPaneHeaderComponent,
  SiListDetailsComponent,
  SiListPaneBodyComponent,
  SiListPaneComponent,
  SiListPaneHeaderComponent
} from '@siemens/element-ng/list-details';
import {
  MenuItem,
  SiMenuBarDirective,
  SiMenuDirective,
  SiMenuHeaderDirective,
  SiMenuItemComponent
} from '@siemens/element-ng/menu';
import {
  BOOTSTRAP_BREAKPOINTS,
  SiResizeObserverDirective
} from '@siemens/element-ng/resize-observer';
import { SiSearchBarComponent } from '@siemens/element-ng/search-bar';
import { SiTabComponent, SiTabPortalComponent, SiTabsetComponent } from '@siemens/element-ng/tabs';
import { LOG_EVENT } from '@siemens/live-preview';
import { NgxDatatableModule } from '@siemens/ngx-datatable';

import { CorporateEmployee, DataService, PageRequest } from '../datatable/data.service';

@Component({
  selector: 'app-sample',
  imports: [
    CommonModule,
    SiListDetailsComponent,
    SiListPaneComponent,
    SiListPaneHeaderComponent,
    SiListPaneBodyComponent,
    SiDetailsPaneComponent,
    SiDetailsPaneHeaderComponent,
    SiDetailsPaneBodyComponent,
    SiDetailsPaneFooterComponent,
    SiIconComponent,
    SiMenuBarDirective,
    SiMenuItemComponent,
    SiSearchBarComponent,
    SiFilterBarComponent,
    NgxDatatableModule,
    SiDatatableModule,
    SiEmptyStateModule,
    SiMenuDirective,
    SiMenuHeaderDirective,
    CdkMenuTrigger,
    SiTabsetComponent,
    SiTabComponent,
    SiTabPortalComponent,
    SiResizeObserverDirective
  ],
  templateUrl: './si-list-details.html',
  providers: [DataService],
  host: {
    class: 'si-layout-fixed-height'
  }
})
export class SampleComponent {
  logEvent = inject(LOG_EVENT);

  private dataService = inject(DataService);
  private cdRef = inject(ChangeDetectorRef);

  /**
   * List details
   */
  expandBreakpoint = BOOTSTRAP_BREAKPOINTS.mdMinimum; // this is the default
  detailsActive = false; // this is the default
  disableResizing = false;

  /**
   * To force a demonstration of the condensed layout, we use a maxWidth
   * value for the whole component.
   */
  maxWidth: number | undefined;

  /**
   * List actions
   */
  listActions: MenuItem[] = [
    {
      type: 'action',
      label: 'Add',
      action: () => this.logEvent('Add triggered')
    }
  ];

  /**
   * Filters
   */
  filters: Filter[] = [
    {
      filterName: 'date',
      title: 'Date',
      description: '27-12-2022'
    },
    {
      filterName: 'location',
      title: 'Location',
      description: 'Zug'
    }
  ];

  /**
   * List data (table)
   */
  cache: any = {};
  isLoading = 0;
  pageNumber = 0;
  pageSize = 50;
  rows: CorporateEmployee[] = [];
  selectedEntity: CorporateEmployee | undefined;
  selectedEntities: CorporateEmployee[] = [];
  tableConfig = SI_DATATABLE_CONFIG;
  totalElements = 0;
  searchTerm?: string;

  /**
   * Details data
   */
  detailsActions: MenuItem[] = [
    {
      type: 'action',
      label: 'Edit',
      action: () => this.logEvent('Edit triggered')
    }
  ];

  onDiscard(): void {
    this.logEvent('Discard');
  }

  onSave(): void {
    this.logEvent('Save');
  }

  datatableOnSelect(): void {
    this.selectedEntity = this.selectedEntities[0];
    this.detailsActive = true;
    this.logEvent(this.selectedEntities);
  }

  searchTermChanged(searchTerm: string): void {
    this.searchTerm = searchTerm;
    this.cache = {};
    this.totalElements = 0;
    this.rows = [];
    this.setPage({ offset: 0, pageSize: this.pageSize, filter: searchTerm });
  }

  setPage(pageRequest: PageRequest): void {
    pageRequest.filter = this.searchTerm;
    // current page number is determined by last call to setPage
    this.pageNumber = pageRequest.offset;

    // if page size changed, the primitive cache can't handle it, so clear
    if (this.pageSize !== pageRequest.pageSize) {
      this.cache = {};
    }
    this.pageSize = pageRequest.pageSize;

    // don't load same data twice
    if (this.cache[pageRequest.offset]) {
      return;
    }
    this.cache[pageRequest.offset] = true;

    // counter of pages loading
    this.isLoading++;

    this.dataService.getResults(pageRequest).subscribe(pagedData => {
      // create array to store data if missing
      if (!this.rows || this.totalElements !== pagedData.page.totalElements) {
        // length should be total count
        this.rows = new Array<CorporateEmployee>(pagedData.page.totalElements || 0);
      }
      // update total count
      this.totalElements = pagedData.page.totalElements;

      // calc starting index
      const start = pagedData.page.pageNumber * pagedData.page.size;

      // copy existing data
      const rows = [...this.rows];

      // insert new rows into new position
      rows.splice(start, pagedData.page.size, ...pagedData.data);

      // set rows to our new rows
      this.rows = rows;

      this.isLoading--;
      this.cdRef.markForCheck();
    });
  }
}
```

Template:

```html
<si-list-details
  #container
  stateId="si-list-details-demo"
  class="p-6 px-md-9"
  listWidthUnit="fr"
  [expandBreakpoint]="expandBreakpoint"
  [disableResizing]="disableResizing"
  [listWidth]="50"
  [minListSize]="200"
  [minDetailsSize]="100"
  [(detailsActive)]="detailsActive"
>
  <si-list-pane class="card">
    <si-list-pane-header>
      <si-search-bar
        class="flex-grow-1"
        placeholder="Search"
        colorVariant="base-0"
        [showIcon]="true"
        (searchChange)="searchTermChanged($event)"
      />
      <button
        type="button"
        class="btn btn-icon btn-tertiary"
        aria-label="Options"
        [cdkMenuTriggerFor]="contextMenu"
      >
        <si-icon class="icon" icon="element-options-vertical" />
      </button>
    </si-list-pane-header>
    <si-list-pane-header>
      <si-filter-bar
        style="width: 0"
        class="flex-grow-1 flex-shrink-1"
        colorVariant="base-0"
        [allowReset]="false"
        [filters]="filters"
        (filtersChange)="logEvent($event)"
      />
      <button
        type="button"
        class="btn btn-icon btn-tertiary-ghost element-filter"
        aria-label="Filters"
        (click)="logEvent('Filters')"
      ></button>
    </si-list-pane-header>
    <si-list-pane-body>
      <div class="si-layout-fixed-height overflow-auto">
        <ngx-datatable
          #table
          class="si-layout-fixed-height table-element focus-inside"
          siDatatableInteraction
          selectionType="single"
          columnMode="force"
          [cssClasses]="tableConfig.cssClasses"
          [rows]="rows"
          [columns]="[
            { name: 'Name', sortable: false },
            { name: 'Role', sortable: false },
            { name: 'Company', sortable: false }
          ]"
          [reorderable]="false"
          [headerHeight]="tableConfig.headerHeight"
          [rowHeight]="tableConfig.rowHeightSmall"
          [footerHeight]="0"
          [ghostLoadingIndicator]="isLoading > 0"
          [scrollbarV]="true"
          [externalPaging]="true"
          [externalSorting]="true"
          [count]="totalElements"
          [offset]="pageNumber"
          [datatableInteractionAutoSelect]="container.hasLargeSize()"
          [(selected)]="selectedEntities"
          (page)="setPage($event)"
          (selectedChange)="datatableOnSelect()"
          (siResizeObserver)="table.recalculate()"
        >
          <si-empty-state empty-content icon="element-users" heading="No users to display" />
        </ngx-datatable>
      </div>
    </si-list-pane-body>
  </si-list-pane>
  <si-details-pane class="card">
    <si-details-pane-header title="Title" [hideBackButton]="false">
      <si-tabset #tabset style="width: 0" class="flex-grow-1 flex-shrink-1">
        <si-tab heading="Overview" [active]="true">
          <div class="si-layout-fixed-height card-body" [class.text-center]="!selectedEntity">
            <p class="card-text">
              @if (selectedEntity) {
                {{ selectedEntity | json }}
              } @else {
                No entity selected.
              }
            </p>
          </div>
        </si-tab>
        <si-tab heading="History">
          <div class="mx-auto text-center">
            @if (selectedEntity) {
              History for {{ selectedEntity.name }}
            } @else {
              No entity selected.
            }
          </div>
        </si-tab>
        <si-tab heading="Advanced" [disabled]="true" />
      </si-tabset>
      <si-menu-bar>
        <si-menu-item icon="element-edit" (triggered)="logEvent('editing')">Edit</si-menu-item>
        <si-menu-item
          icon="element-refresh"
          aria-label="Refresh"
          (triggered)="logEvent('refreshing')"
        />
      </si-menu-bar>
    </si-details-pane-header>
    <si-details-pane-body>
      <si-tab-portal class="si-layout-fixed-height overflow-auto pt-4" [tabset]="tabset" />
    </si-details-pane-body>
    <si-details-pane-footer class="justify-content-end">
      <button type="button" class="btn btn-secondary" (click)="onDiscard()">Discard</button>
      <button type="button" class="btn btn-primary" (click)="onSave()">Save</button>
    </si-details-pane-footer>
  </si-details-pane>
</si-list-details>

<ng-template #contextMenu>
  <si-menu>
    <si-menu-header>Actions</si-menu-header>
    <si-menu-item icon="element-sort-down" disabled>Sort</si-menu-item>
    <si-menu-item icon="element-refresh" (triggered)="logEvent('refreshing')">Refresh</si-menu-item>
  </si-menu>
</ng-template>
```

## How to enable the UI state storage

The storing of UI State is disabled by default. It requires two steps to enable it for a specific component.

1. Include `provideSiUiService` in your app configuration / `AppModule` to enable it in general:

```
import { ApplicationConfig } from '@angular/core';
import { provideSiUiState } from '@siemens/element-ng/common';

const config: ApplicationConfig = {
  providers: [provideSiUiState()]
};
```

1. Set the `stateId` on supported components like the

```
<si-navigation-vertical stateId="navVertical" />
```

With those two changes, the expand/collapse state will now be saved.

## Using a custom storage

If enabled, the UI state is stored by default in the `localstorage`. Applications can override this by implementing a custom store:

```
import { UIStateStorage } from '@siemens/element-ng/common';

@Injectable()
class MyUIStateStorage implements UIStateStorage {
  save(stateId: string, data: string): void | Promise<void> {
    // Save the for the provided stateId. Override any existing data for that ID.
    // Handle errors here. Otherwise the will just be retrhown.
  }

  load(stateId: string): string | undefined | null | Promise<string | undefined | null> {
    // Load the data by stateId. Return undefined or null if nothing was stored previously.
    // Handle errors here. Otherwise the will just be retrhown.
  }
}
```

The custom storage needs to be configured on initialization of the `SiUIState`:

```
import { ApplicationConfig } from '@angular/core';
import { provideSiUiState } from '@siemens/element-ng/common';

const config: ApplicationConfig = {
  providers: [
    provideSiUiState({
      store: MyUIStateStorage
    })
  ]
};
```

### [provideSiUiState](<https://github.com/siemens/element/blob/main/projects/element-ng/common/services/si-uistate.service.ts#L134-L139>)

**Kind:** constant

```
import { provideSiUiState } from '@siemens/element-ng/common';
```

Enables the automatic storage of UI state for enabled components.

```
(config?: { store?: Type<UIStateStorage> | undefined; } | undefined) => Provider[] = ...
```

```
provideSiUiState(config?: { store?: Type<UIStateStorage>; }): Provider[]
```

Enables the automatic storage of UI state for enabled components.

#### Parameters

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| [config](<https://github.com/siemens/element/blob/main/projects/element-ng/common/services/si-uistate.service.ts#L134-L134>) (optional) | `{ store?: Type<UIStateStorage>; }` |  |  |

**Returns:** [Provider](<https://angular.dev/api/core/Provider>)`[]`

### Types Documentation

### [UIStateStorage](<https://github.com/siemens/element/blob/main/projects/element-ng/common/services/si-uistate.service.ts#L22-L44>)

**Kind:** interface

```
import type { UIStateStorage } from '@siemens/element-ng/common';
```

Interface that defines a UIStateStore. It must be provided via [provideSiUiState](<index.html#t:provideSiUiState>).

```
interface UIStateStorage
```

#### Methods

##### load

[Source for load](<https://github.com/siemens/element/blob/main/projects/element-ng/common/services/si-uistate.service.ts#L43-L43>)

Loads data for a specific stateId. Can be asynchronous.

Errors should be handled by the implementation. The `SiUIStateService` does not handle errors.

Returns: The data or undefined if the data does not exist. Asynchronous implementations must return a [Promise](<https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise>) containing the data.

```
load(stateId: string): string | Promise<string | null | undefined> | null | undefined
```

#### Parameters

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| [stateId](<https://github.com/siemens/element/blob/main/projects/element-ng/common/services/si-uistate.service.ts#L43-L43>) | `string` |  |  |

**Returns:** [string](<https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String>)`  |  `[Promise](<https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise>)`<`[string](<https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String>)`  |  `[null](<https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null>)`  |  `[undefined](<https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined>)`> | `[null](<https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/null>)`  |  `[undefined](<https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined>)

##### save

[Source for save](<https://github.com/siemens/element/blob/main/projects/element-ng/common/services/si-uistate.service.ts#L31-L31>)

Saves data under a specific stateId. Already existing data for that stateId should be overridden. Asynchronous implementations must return a [Promise](<https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise>) and resolve it once saving was completed.

Errors should be handled by the implementation. The `SiUIStateService` does not handle errors.

```
save(stateId: string, data: string): void | Promise<void>
```

#### Parameters

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| [stateId](<https://github.com/siemens/element/blob/main/projects/element-ng/common/services/si-uistate.service.ts#L31-L31>) | `string` |  |  |
| [data](<https://github.com/siemens/element/blob/main/projects/element-ng/common/services/si-uistate.service.ts#L31-L31>) | `string` |  |  |

**Returns:** [void](<https://www.typescriptlang.org/docs/handbook/2/functions.html#void>)`  |  `[Promise](<https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise>)`<`[void](<https://www.typescriptlang.org/docs/handbook/2/functions.html#void>)`>`
