Create a keyup function that triggers an alert message if the user's input does not meet the

Hello, I'm looking for some assistance with a coding problem. Basically, I have an array of numbers which includes 5, 8, and 10. I need to create a form where users can input numbers. If the user inputs a number that is not 5, 8, or 10, I want to display an error message using (keyup) event. The error message should simply say "Wrong number length" in red color. Can anyone help me out with this?

Answer №1

let numbers = [2, 4, 6];
@ViewChild('inputElement') inputElement: ElementRef;

Make sure to assign a local reference #inputElement to your HTML input element. Then, in your TypeScript file, create an observable after the component has been initialized, for example, in ngAfterViewInit.

const textInput$ = fromEvent(this.inputElement.nativeElement, 'keyup').pipe(
                        debounceTime(500),
                        map(event => event as KeyboardEvent),
                        map(event => (event.target as HTMLInputElement).value),
                        distinctUntilChanged(),
                      );
textInput$.subscribe(input => {
                    if (numbers.includes(input.length)) {
                      displayError();
                    }
                  });

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

Is it possible to change the value of a react-final-form Field component using the onSelect function?

I am currently working on a React application using TypeScript and incorporating the Google Places and Geocoder APIs through various React libraries such as "react-places-autocomplete": "^7.2.1" and "react-final-form": "^6.3.0". The issue I'm facing ...

Notifying users when a document is nearing its expiration date in the most effective manner

In my calendar app, I set appointments to automatically delete after 5 minutes. Now, I want to retrieve all appointments that are about to expire within 1 minute and send a notification to the front-end indicating their impending expiration. Although I at ...

Function that sets object properties based on specified keys and verifies the value

Let's consider a scenario where we have an object structured like this: interface Test{ a: number; b: string; c: boolean; } const obj:Test = { a: 1, b: '1', c: true, } We aim to create a function that can modify the value ...

Learn how to dynamically import external modules or plugins using the import() functionality of TypeScript 2.4 within the production script generated by Angular CLI

Utilizing the typescript 2.4 [import()][1] feature has proven to be effective for dynamically loading modules. Testing this functionality has shown positive results, especially when importing modules and components located within the same directory. Howev ...

What causes the difference in inference for unspecified generics between a simple function call and a null-coalescing operator in TypeScript?

What causes the different types of a and b in the given code snippet? function empty<T>() { return [] as T[] } const defEmpty = empty() function test1(abc: number[]|null) { const a = abc ?? defEmpty const b = abc ?? empty() } Upon testing on t ...

The 'isLoading' property is not found in the type 'UseMutationResult<AxiosResponse<any, any>, Error, void, unknown>'.ts(2339)

I'm currently working on implementing a delete functionality that displays a loading state using the useMutate function from tanstackquery. However, I encountered an issue where the loading state is not shown when I click the delete button, even after ...

Angular 5 is throwing an invalid response during preflight

I am attempting to make an HTTP request to a server using the HTTP library in Angular 5 like so: return this.http.post('http://localhost/api-panel/index.php/admin-api-user/check-session', []); This is how I am subscribing to the HTTP observable ...

Angular 4 after ejection, coupled with automated end-to-end testing using Protractor/Selenium setup

I am attempting to conduct end-to-end tests using Protractor/Selenium on an Angular 4 project that has been ejected. Here is my package.json: ... "scripts": { "pree2e": "webdriver-manager update --standalone false --gecko false --quiet node", "e2 ...

The combination of arrays and array methods in intersection types may encounter difficulty in accessing all fields

I have two different types, both in the form of arrays of objects with specified fields, combined into an intersection type in Typescript. When I access an element from the array, I can retrieve the second field without any issues. However, when I try to ...

SecurityClient is encountering a problem where the Http Error status is not being displayed

Currently, I am utilizing a custom Http client that is an extension of Angular 4's Http Client. export class SecurityClient extends Http { // ... } Within this client, there are methods designed to make calls to an API and handle a 401 status code by ...

Encountering a compilation error while trying to utilize a union type in a function parameter within an

As stated on https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html, it is recommended to utilize multiple types for a parameter in a function (refer to the union part) /* OK */ interface Moment { utcOffset(): number; ...

Setting up a .NetCore3.1 API on LinuxCentos with Nginx

Currently, I am facing an issue while attempting to deploy a .NET Core 3.1 API + Angular application on Linux Centos. The application runs fine on the server; however, the browser fails to load it properly. Surprisingly, when I publish the same project for ...

The dtOptions property cannot be bound to the table as it is not recognized as a valid property

Encountering an Issue Current Problem Description Desired Outcome Check out the with-options Detailed Steps for Reproducing the Issue Can't bind to 'dtOptions' since it isn't a known property of 'table'. (" <nb-ca ...

Guide on converting a material datepicker date value into the format "MM-DD-YYYY" in Angular 6

I need help formatting the date below to MM-DD-YYYY format in my Angular 6 project. I've checked out various solutions on SO and other websites, but so far, none have worked for me. Currently, I am using Material's Angular DatePicker component. ...

Discover the Magic of Angular 8 and Bootstrap 4 Tooltips

I'm trying to implement tooltips from Bootstrap 4 into my web application. According to Bootstrap documentation, I should initialize the tooltips with the following code: $(function () { $('[data-toggle="tooltip"]').tooltip() }) (Implement ...

Unlock specific elements within the "sub-category" of a combined collection

If my union type is structured like this: type StateUpdate = { key: 'surname', value: string } | { key : 'age', value: number }; This setup is convenient because it allows me to determine the type of the value based on the key. Howev ...

Determining if an emitted event value has been altered in Angular 4

I am currently working on an Angular 4 project. One of the features I have implemented is a search component, where users can input a string. Upon submission of the value, I send this value from the SearchComponent to the DisplayComponent. The process of ...

Stop Node Modules from Referencing Global Location

Recently, I ran into an issue after updating my project from Git. The problem arose when trying to use ngx-material-timepicker in conjunction with the luxon library. (It's important to note that ngx-material-timepicker isn't a new addition to th ...

Headers cannot be modified after they have been sent to the client in Node.js and Angular

I am working on developing login and registration services using Nodejs Express. Every time I make a request in postman, I consistently encounter the same error: https://i.stack.imgur.com/QZTpt.png Interestingly, I receive a response in postman (register ...

Updating the checkbox status in Angular when the radio button value is changed

I need help with a feature where all the checkboxes are checked based on the value of a radio button, and vice versa when an unchecked radio button is clicked. I have tried to implement this functionality using the following code but have not been successf ...