Using <number | null> or <number | undefined> in computed() or signals() doesn't work...

Discussão em 'Angular' iniciado por LetzFlow, Março 20, 2025.

  1. LetzFlow

    LetzFlow Guest

    I'm trying to use singals and computed in my new Angular project, but I'm running into a problem.

    I have a computed value, which contains an id, which is a number. This id will be set by user interaction. Before that it is not set, so I tried setting it to null (or undefined).

    public someSignal = signal<number | null>(null);
    public selectedId = computed(() => {
    var result: number | null = null;
    let value = someSignal();
    // do some computations
    return result;
    });


    Now I wanted to use this in the template.

    <div *ngIf="selectedId() as id">Current id: {{ id }}</div>


    But this only works if the id is not 0. As soon as it is zero it behaves as if it is null. I switched everything to number | undefined, but it resulted in the same problem. As far as I know there is only the special case of null >= 0 being true. But maybe something changed or signals and computed values work differently.

    I know I can change it to -1 representing the "null" value, but I would like to know if there is some better solutions to use number | null or if that's just something we have to life with.

    Thank you very much.

    Continue reading...

Compartilhe esta Página