Limiting @Input Value to a Certain Number Range using Angular

I need to include an InputSignal in my Angular component that only accepts arrays of numbers. Each number in the array should fall between 0.01 and 10, and cannot have more than 2 decimal places.

It is important to enforce these restrictions to ensure that developers are notified if the input does not comply with the specified criteria. How can I define the type of this InputSignal or set constraints to achieve this?

export class MyComponent {
public readonly value: InputSignal<valueType[]> = input<valueType[]>([]);
}

Answer №1

Using the transform function for validation, we can throw an error using throw new Error(...) to display an error message in the console!

import { Component, InputSignal, input } from '@angular/core';
import { bootstrapApplication } from 'angular/platform-browser';
import 'zone.js';

@Component({
  selector: 'app-child',
  standalone: true,
  template: ``,
})
export class Child {
  public readonly value: InputSignal<any[]> = input<any[], any[]>([], {
    transform: (data: any) => {
      const found = data.some((item: any) => item <= 10 && item >= 0.01);
      if (found) {
        throw new Error(
          'Array should not contain values greater than 10 and less than 0.01'
        );
      }
      return data;
    },
  });
}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [Child],
  template: `
    <app-child [value]="[1,2,3,4,100]"/>
  `,
})
export class App {
  name = 'Angular';
}

bootstrapApplication(App);

Click here for Stackblitz Demo

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

Having trouble displaying real-time camera RTSP streaming using Angular

I am currently in the process of developing a web application using Angular and I need to incorporate a window that displays live RTSP streaming. Upon conducting research, I discovered that this can be achieved by utilizing the JSMpeg JavaScript library. ...

Exploring the application of styles within the shadow DOM

I'm experimenting with applying styles to the shadow DOM. Consider the following example: const element = document.getElementById("bar"); const shadowRoot = element.attachShadow({ mode: "open" }); const greeting = document.createElement("p"); gree ...

Transitioning Ionic2 RC0 - relocating custom libraries to the build directory after the removal of gulp

https://i.sstatic.net/0KLac.png The Gulp tool has been removed by the Ionic Team from their project. What is the alternative method to set up libraries? ...

Guide to simulate the store.pipe method in an Angular component during unit testing

Just starting out with Angular and I'm trying to write unit tests for a component that retrieves data from the store. I've mocked both the service files and the store itself, but when running the test, I keep encountering the following error. Eve ...

Uploading images using multipart in react is causing an error and cannot be completed

Trying to upload images in the database using multipart is causing an error from the API saying 'Files can't be uploaded". Checking the API in postman shows it is working fine there. There seems to be an issue with my code, but I can't ...

Utilizing Dynamic Variables in Angular 4 Templates

Hey everyone, I recently created an Angular 4 app and developed a component called Contentholder. The Contentholder consists of HTML & CSS to display the content holder that I am utilizing. When I include <content-holder></content-holder>, ...

Consolidate type definition within a tsx file using VS Code

Whenever I define a type in a TypeScript file (.ts) on VS Code, I notice that there is no option to collapse the definition. Here's an example: export type Test = { someValue: string, someOtherValue: string, yetAnotherValue: string }; I ...

Optimal Strategies for Handling CORS in Angular 2+ and Node/Express Servers

Currently, I am in the process of implementing user authentication with Express/Node and testing cookies from an Angular frontend. Upon logging in, the cookies are properly displayed in the network tab but not in the application tab. I understand that usi ...

Revamp label titles in Ionic/Angular by incorporating a hyperlink for updating the image

Seeking guidance on changing labels in an Ionic/Angular app from 0, 1, 2 to Profile, Group, and Friend. Despite utilizing resources like Google and YouTube, I've struggled for days to make this adjustment without success. Any assistance would be great ...

Why is the format incorrect when the Angular 7 (Change)-Function on Input of type Date isn't functioning?

I am facing an issue with updating the date using key input and assigning the selected date to a property of my object. Below is the code I'm currently working with: <input type="date" [value]="dateTime()" (change)="setDate($event)"/> The dat ...

incorporating a personalized HTMLElement using Typescript

Hey there! I'm fairly new to using Angular and could use some help. I'm trying to insert a custom HTML element onto a page when a button is clicked, but I'm struggling to figure it out. Here are my HTML and TypeScript files: TypeScript Fil ...

Capable of retrieving response data, however, the label remains invisible in the dropdown menu

Upon selecting a country, I expect the corresponding city from the database to be automatically displayed in the dropdown menu. While I was able to retrieve the state response (as seen in the console output), it is not appearing in the dropdown menu. Inte ...

Transferring all instructions to a subordinate element within the component

I have developed a set of custom directives specifically for <input> elements. Additionally, I have created a custom component called <app-decorated-input>. Within my application, there are numerous instances of both <app-decorated-input> ...

Converting JSON data to an Excel file in an Angular application

I'm working on exporting my JSON data to an XLSX file. Despite successfully exporting it, the format in the Excel file isn't quite right. Below is the code I am using: downloadFile() { let Obj = { "data": [12,123], "date": ["2018-10- ...

The property 'x' is not found on 'Reel' type in this context

Creating a custom class extending Container in PIXI.js: export class CustomContainer extends Container { constructor(width: number, height: number) { super(); var sprite: Sprite = Sprite.fromImage("assets/images/elephant.png"); ...

Encountered an issue trying to access undefined properties while reading 'PP'

I am trying to showcase the data retrieved from my JSON file. Here is a glimpse of the information stored in the JSON => Within DTA > PP , I am specifically interested in displaying the variable NOMFAMILLE. An error message has caught my attentio ...

Angular's ngClass directive failed to be applied correctly

I am currently experimenting with the use of [ngClass] in Angular and it appears that it is not being applied as expected. Interestingly, [ngStyle] for similar CSS styles is working without any issues. What could I be doing wrong in this scenario? There ar ...

Avoiding duplicate subscriptions in Angular 4/5: a guide to streamlining

I'm looking for a streamlined way to capture a query parameter and subscribe to an API in order to retrieve results. Currently, I am using combineLatest but it seems a bit excessive. Is there a more efficient approach that focuses solely on the queryP ...

OneGraph and Graphql Codegen produce enums with numerical representations

After migrating my project's codebase from using the direct Headless Wordpress GraphQL endpoint to OneGraph for Google+Facebook Business support, I encountered an error related to apollo referencing the output codegen. Here is the specific error messa ...

In Angular and Jasmine, it is important to note that when multiple actions are included within an it() function, they

I'm currently working on a test to ensure that each INPUT field is not empty. I seem to be facing some challenges in writing this test, which could be due to my lack of experience or the limitations of Jasmine when it comes to handling multiple action ...