Enforcing rigorous data type validation for @Input in components

Check out this sample demo that I've put together.

In the code, I'm passing a value of ipNumber = '99'; to the component HelloComponent.

The issue arises with the @Input, which is defined as

@Input() someVal : number;

I aim to receive an error when a string is passed through @Input.

To resolve this, the correct input should be

ipNumber = 99;

Instead of

ipNumber = '99';

Answer №1

To ensure the validity of your input, consider utilizing the ngOnChanges Lifecycle hook.

ngOnChanges(changes: SimpleChanges) {
        const typeOfName = typeof changes['name'].currentValue;
        if (typeOfName !== 'string') {
          console.warn(`You provided ${typeOfName} instead of a string as expected`);
        }
      }

For more information, refer to this article:https://medium.com/@abdelelmedny/angular-input-decorators-5d38089070aa

Answer №2

Placing the code inside the constructor will not be effective since the angular component's life cycle has not reached that point yet. It would be better to place it in the ngOnInit method or a separate function that can be called within the ngOnInit or any subsequent life cycle event. Please refer to the code snippet below:

ngOnInit() {
     if(typeof this.someVal !== 'number') {
      console.error("This is not a number");
    }
  }

Answer №3

One effective method to verify the type of an @Input is by utilizing JavaScript's typeof function. This allows us to determine whether the provided value is a number or not, enabling us to handle errors accordingly.

export class HelloComponent implements OnInit {
  @Input() name: string;
  @Input() someVal : number;

  constructor(){

  }

  ngOnInit() {
    console.log(this.someVal)

    if(typeof this.someVal !== "number" ) {
      throw new Error('Please provide only number');

    }
  }


}

Click here for the solution on stackblitz

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

Coinciding titles within flot pie chart

I am facing an issue with overlapping labels in my pie charts generated using jquery flot, especially when the chart pieces are very small. Is there a recommended solution to prevent this overlap? Below is the configuration for my current pie chart: ser ...

After changing the form action using jQuery, the GET variables mysteriously vanish

I am attempting to modify the action URL of a form using jQuery. Below is the code I have implemented: <form id='form_a' action='browse.php' method='get'> <input type="submit" value="Filter" id='but_a'& ...

Error message: "Unable to access D3 data when trying to select nested

Working with JSON data in D3 is proving to be a challenge for me. The file seems to be properly read, as indicated by its appearance when I use console.log, and it appears to be correctly formatted based on the examples I have come across. However, when I ...

When it comes to using jQuery, I find that it only functions properly when I manually input the code into the Google Chrome console. Otherwise

Below is the HTML snippet: <textarea cols="5" disabled id="textareRSAKeypair"> @Model["keypair"] </textarea> <a href="#" class="btn btn-primary" id="downloadKeypair">Download Key</a> Here is the jQuery code: <script src="ht ...

How to loop through an array in javascript and calculate the total?

Hey there! I'm a bit confused and couldn't find the solution anywhere. Are you able to take a look at my code and point out what's wrong with it? I promise, I'm not trying to get you to do my homework! Question: Loop through an array F ...

Two separate buttons in two distinct views that trigger the same function in AngularJS

I am currently working on a Single Page Application (SPA) that has two distinct views - one for subjects and another for students. In the subject view, there is a save button located in app/views/subject/subject.html: <button type="button" class="b ...

Encountering a build error while using npm and node-gyp

When attempting to install client-session using npm, I encountered an error. I also tried to install node_gyp using npm, as well as cloning it using git, but the node gyp error persisted. Unfortunately, I could not locate proper documentation on the root ...

Pending activation of the Timer Fired event

Below is some code I have for implementing swipe gesture functionality: this.topSlide = this.elementRef.nativeElement.querySelector('.product_rate_slide'); if (this.topSlide) { this.topSlide.addEventListener('touchstart', this.hand ...

Launching an Angular application beyond the typical Angular framework

I want to develop an Angular 7 app by following a tutorial that provides the default page template. ng new my-app After reviewing it using ng serve --o and confirming its functionality, I am struggling with how to deploy it outside of Angular. I tried ru ...

Sliding Up Bottom Navbar Effect using HTML, CSS, and JS

I've been doing some research, but I can't seem to find exactly what I'm looking for. My objective is to implement a navigation bar at the bottom of my JS-app so that when a user clicks on a specific button, an animation will trigger causing ...

Subscribing to an observable and storing it as a string in a collection is

Being relatively new to TypeScript and JavaScript, I am struggling with understanding how collections and file input/output operations function. Specifically, my challenge lies in retrieving data from a JSON file and storing it in a collection. Below is t ...

Achieve scroll functionality in bootstrap modal

In my application, I am utilizing a bootstrap modal feature that contains lengthy content. Interestingly, I have encountered an issue with two different modals on separate pages. While viewing the modals on mobile devices, I noticed that one of them can be ...

What is the process of integrating an HTML web component with an HTML file? Can I use innerHTML = foo("myfile.html") to achieve

Using HTML web components allows me to define their code using this method: this.innerHTML = `<h1></h1>`; However, I find it cumbersome as I do not have access to the Emmet Abbreviation feature which slows down my component creation process. ...

Steps for sending JSON data to a specific endpoint in an API

I recently developed a simple API using Node.js. Here is the code snippet: const Post = require('../models/article'); ... router.post('/contribute', (req, res) => { console.log('Adding new article'); let userPost = ...

AntDesign is throwing an error stating that resetFields is not a function when using

I'm facing an issue with resetting the fields in my form. The form allows users to add more forms, and so on... Upon successful validation, I want to save the data in my DB and store AND reset all input fields in the form. Unfortunately, I'm un ...

Is it possible to implement a loading animation that remains visible until the entire page has finished loading?

After deploying my website on netlify, I noticed that only the HTML content is displayed until the page finishes loading. Does anyone have advice on how to make the website visible only after it has fully loaded? I have created a custom loading animation, ...

Is it possible to close a tab while the chrome extension popup is still active?

I am currently developing a Chrome extension that reads the content of the current tab and performs a heavy task on the backend. If I were to close the tab while the process is ongoing, how can I allow the user to do so without waiting for the task to fi ...

What is the process for transforming raw text data into json format?

After receiving a response from the API mentioned below, I have been attempting to transform the data into a JSON array without much success. found=100 items[0].Detail.Address=192.168.1.4 items[0].Detail.Type=CGI items[0].Device= items[0].Level=0 items[0]. ...

What is the best way to set up a function to automatically execute on a specific date and time

I am facing a challenge with my website where users can send themselves messages at a chosen date and time. However, I am unsure how to trigger the message delivery at the specified time. While I am aware of CronJobs, they seem more suitable for recurring ...

Customize the Color of the Selected Button on the Menu (Implementing Ant Design Components in React)

Hello, I am reaching out to inquire about the process of updating the menu associated with a specific button in Ant Design using React. I am interested in changing the options that are displayed when the button is clicked. I would greatly appreciate any g ...