When utilizing <number | null> or <number | undefined> within computed() or signals(), it may not function properly if the value is 0

I've encountered an issue while implementing signals and computed in my new Angular project.

There's a computed value that holds an id, which is initially not set and will be assigned by user interaction. To handle this initial state, I attempted to set it to null or undefined.

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

I wanted to use this functionality in the template.

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

However, I noticed that this only works when the id is not 0. If the id is zero, it behaves as if it is null. I tried changing everything to number | undefined, but encountered the same issue. It seems that null >= 0 evaluates to true, but I'm unsure if there have been any changes in how signals and computed values are handled.

I could work around this by using -1 to represent "null," but I would appreciate knowing if there are better solutions for working with number | null, or if this is something we simply have to deal with.

Thank you for your help.

Answer №1

To modify the structure, you should consider sending the function as an arrow function within the computed section below! Ensure that you also establish a signal within the computed, so that changes can be automatically detected and the value updated alongside any intricate calculations!

import { NgIf } from '@angular/common';
import { Component, computed, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [FormsModule, NgIf],
  template: `
    <input type="text" [(ngModel)]="input"/>
    <div *ngIf="selectedId() as id">Current id: {{id}}</div>
  `,
})
export class App {
  public input = signal<number | null>(null);

  public selectedId = computed(() => {
    var result: number | null = this.input();
    // perform certain computations
    return `result-${result}`;
  });
}

bootstrapApplication(App);

Check out Stackblitz Demo here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to implement debounce in handling onChange events for input fields in React

I've been attempting to implement debounce functionality in my React app without relying on external libraries like lodash or third-party node modules. I've tried various solutions found online, but none have worked for me. Essentially, in the h ...

Unable to locate module within Typescript

Hello everyone, I am facing a problem similar to this one: I have an app written in TypeScript, and within it, I have imported import { Component } from '@angular/core'; import {CORE_DIRECTIVES} from '@angular/common'; import { MODA ...

Filtering Deno tests by filename: A step-by-step guide

How can I selectively run Deno tests based on their filenames? Consider the following test files: number_1_test.ts number_2_test.ts string_test.ts If I want to only run tests with filenames starting with number*, I am unable to use either of these comma ...

What causes the discrepancy in results between these two NodeJS/Typescript imports?

Within my NodeJS project, I have integrated typescript version 3.2 alongside express version 4.16 and @types/express version 4.16. My development is focused on using Typescript with the intention of transpiling it later on. The guidelines for @types/expre ...

Tips on ensuring the callback function is properly called when it is passed as an argument to another function

I am facing a challenge with my typescript method that needs to call another method, on(), which requires a callback method. I want the myConnect() method to wait until the callback is executed. I believe this involves using a promise, but I'm struggl ...

What is the best way to customize a MaterialUI outlined input using a global theme overrides file?

I've been working on customizing my theme file with overrides, and I've encountered a strange bug while trying to style the outlined input. It seems like there are two borders appearing when these styles are implemented. https://i.stack.imgur.co ...

Error occurred when attempting to link user services with report controller

Greetings, I am currently working on a Nest Js mini project that consists of two separate modules: reports and users. Each module has its own Service, controller, and repositories. The reports module has a many-to-one relation with the users module. My g ...

Sort through a list of objects by certain properties

I'm currently dealing with two arrays: one contains displayed columns and the other contains objects retrieved from a database, with more attributes than the displayed columns. displayedColumns = ['CompanyName','Ticker', 'Id& ...

Navigating through various Angular 7 projects in Express using JWT authentication and role-based routing

In my Angular 7 project, I have developed multiple applications for different roles such as admin, user, and editor. Each role has its own set of components and views. When a logged-in user accesses the application, they are directed to their respective r ...

What could be the reason for `process.env.myvariable` not functioning in a Next.js project with TypeScript

After creating a file called .env.local in the root directory of my project, I added a variable called WEBSOCKET_VARIABLE=THIS_IS_TEXT to it. However, when I try to access it using process.env.WEBSOCKET_VARIABLE, nothing is found. What could be causing ...

Standardized identification code

My request response needs to be defined, but the key name may vary. It will always be a string, but the specific key depends on the request. These are the possible responses: { someRequest: { message: 'success', status: 200 } } { someOtherReques ...

Using Ionic 4 and Angular 7 to make straightforward remote HTTP requests with Cross-Origin Resource

I'm still navigating my way through ionic and angular, trying to understand how to send a basic HTTP request to a remote server without dealing with CORS. My initial attempt involved the following code snippet: this.httpClient.get<MyObj>("/api" ...

Typescript Server Problem: Critical Error - Mark-compacts Inefficiently Close to Heap Limit, Allocation Unsuccessful - JavaScript Heap Exhausted

Whenever I run my CRA project, I consistently encounter this error in my console. It seems to be related to the typescript server. Is there a solution for this issue? 99% done plugins webpack-hot-middlewarewebpack built preview 7c330f0bfd3e44c3a97b in 64 ...

Step-by-step guide to developing an Angular 2+ component and publishing it on npm

I need assistance with creating an AngularX (2+) component and getting it published on npm. My objective is to publish a modal component I developed in my current Angular App, though currently, I am focusing on creating a <hello-world> component. It ...

Struggling with the functionality of Angular Material Layout Directives

Looking to implement the Child-Alignment feature in Angular Material but running into some issues. Details available here: https://material.angularjs.org/latest/layout/alignment Despite trying to import import { LayoutModule } from '@angular/cdk/l ...

Encountering an issue while trying to launch an Angular application on localhost. Vendor.js resource failed to load

Whenever I compile the code, it runs successfully. However, when I try to serve the application using 'node --max-old-space-size=8192', even though it compiles without any errors, when I open the app in a browser, it returns an error saying "Cann ...

What is the best way to maintain the correct 'this' context for a function that is outside of the Vue

I'm struggling with my Vue component and encountering some errors. <script lang="ts"> import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, va ...

exploring alternatives to ng-container in angular-4.x for selecting elements

Currently in my Angular 4.x project, I have a component using the Selector 'abc' as shown below: @Component({ selector: "Abc", templateUrl: "Abc.html", styleUrls: [ "Abc.css" ] }) However, the "Abc" tag is also present in the DOM, b ...

Incorporate a module that was developed locally into your project

Attempting to incorporate a locally developed Angular project/module into an angular application without having to publish it on the npm repository has been quite a challenge for me. To begin with, I decided to follow a tutorial that guided me through bui ...

When an import is included, a Typescript self-executing function will fail to run

Looking at this Typescript code: (()=> { console.log('called boot'); // 'called boot' })(); The resulting JavaScript is: (function () { console.log('called boot'); })(); define("StockMarketService", ["require", "exp ...