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

Angular 2 file upload encountering CORS issue leading to 401 unauthorized error

Encountered a "401 Unauthorized" error in Chrome and Firefox while attempting to upload files using angular 2 CLI to an apache2-server with a PHP backend. Despite trying three different node modules, the issue persists from the OPTIONS-preflight stage, ...

Ways to attain a similar format - input map

After pressing the save button, I am aiming to achieve the following effect: "timeTable":{ "0": [{"from":"08:00","to":"12:00"}, {"from":"14:00","to":"18:20&q ...

The module '@ngmodule/material-carousel' could not be located

Having an issue with Angular 8 where I am encountering an error when trying to import the @ngmodule/material-carousel module. The specific error message is: Cannot find module '@ngmodule/material-carousel' Package.json "private": true, "depen ...

Continue iterating using (forEach, map,...) until the object (children) has no more elements

I need to disable the active status for all elements within my object structure. Here is an example of my object: const obj = { name: 'obj1' , ative: true , children: [ { name: 'obj2' , ative: true , children: ...

Leveraging the power of map in an Angular typescript file

I've been attempting to populate a Map in Angular by setting values dynamically. When certain buttons are clicked, the onClick function is invoked. typeArray: Map<number,string>; Rent(movieId: number){ this.typeArray.set(movieId,"Rental ...

Transfer the HTTP functionality to a separate service using Angular2 and TypeScript

Currently diving into learning Angular2 and TypeScript after years of using Angular 1.*. I have a top level component that has a property derived from a custom type created in another class. When ngOnInit() is triggered, it makes an HTTP call to a mock RES ...

Progress Bar Modules

I am currently working on creating a customizable animated progress bar that can be utilized as follows: <bar [type]="'health'" [percentage]="'80'"></bar> It is functional up to the point where I need to adjust different p ...

Exploring the benefits of useContext in Expo router

Currently, I am working with the latest Expo-Router version which incorporates file-based navigation. To establish a universal language context in my application, I have utilized React's context API along with the useReducer hook. However, I am encoun ...

Testing a function that utilizes Nitro's useStorage functionality involves creating mock data to simulate the storage behavior

I have developed a custom function for caching management, specifically for storing responses from API calls. export const cache = async (key: string, callback: Function) => { const cacheKey = `cache:${key}`; const data = await useStorage().get ...

Choosing between Angular's Observable and Subject as a DataSourceWhen it comes

I am currently working on an Angular 7 application that utilizes Mat Tables to retrieve data from an API. I have implemented dynamic pagination values, where the pageSizeOptions value changes based on a dropdown selection when loading the grid. By default, ...

What is the best way for me to use a ternary operator within this code snippet?

I'm in the process of implementing a ternary operator into this snippet of code, with the intention of adding another component if the condition is false. This method is unfamiliar to me, as I've never utilized a ternary operator within blocks of ...

Is there a way for me to retrieve the header values of a table when I click on a cell?

I have a project where I am developing an application for booking rooms using Angular 2. One of the requirements is to be able to select a cell in a table and retrieve the values of the vertical and horizontal headers, such as "Room 1" and "9:00". The data ...

When using @Viewchild, it can sometimes lead to encountering

Within my project, I have a component called SideToggleComponent that contains a function: activeButton(value){ ... } I am trying to call this function from another component called BlogComponent. To do so, I am using @ViewChild as shown below: @ ...

The publish-subscribe feature appears to be ineffective

Recently starting with meteor, I learned about the importance of removing autopublish. So, I decided to publish and subscribe to a collection in order to retrieve two different sets of values. Here is the code on my meteor side: Meteor.publish('chann ...

How can I simulate event data while testing a function that is triggered when an event is emitted from another component in Angular integration testing?

Within component A, there is a function responsible for updating the view based on data emitted from component B. The aim is to simply call this function and pass the data without integrating with component B as it would be too complicated for this particu ...

Unsure how to proceed with resolving lint errors that are causing changes in the code

Updated. I made changes to the code but I am still encountering the following error: Error Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. It is recom ...

Definition for intersecting types

I am trying to define a function that can take two objects of different types but with the same keys: function myFunc(left, right, keys) { // simplified: for (const key of keys) { console.log(key, left[key] === right[key]) } return { left, rig ...

Angular 7 running slowly when refreshing or changing routes

Operating System: Ubuntu 16.04 Node Version: v10.15.1 NPM Version: 6.4.1 I have recently developed a web application with two pages using less and HTML without any AJAX calls. Below is the content of my package.json file: { "name": "frontend", "vers ...

Adjust the height, width, and color of the "kendo-switch" widget

I am looking to customize the height, width, and color of the "kendo-switch" component. I attempted to modify the element's style directly, but it did not have the desired effect. What would be the most effective approach for achieving this customiza ...

Retrieve all items that match the ids in the array from the database

I'm having trouble receiving a list of items that match with my array of ids. Here's a snippet from the Angular component code: this.orderService.getSpecyficOrders(ids) .subscribe(orders => { ... Where ids is an array of [{_id : ID }, ...