Angular Input Validator for Minimum and Maximum Values

I've been struggling to restrict the input for years to a range of 0-24, but all my attempts have failed. Does anyone have any suggestions on how to achieve this? relevant code snippet from form.html :

<mat-card>
    <h1>Add Customer</h1>
    <form #customerForm="ngForm">
        <mat-form-field>
                <input 
                    matInput placeholder="Education years"
                    [(ngModel)] = "years"
                    name = "years"
                    min = "0"
                    max = "24"
                    required="required">
        </mat-form-field>
    </form>
    </mat-card>

relevant code snippet from form.ts :

import { Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
import { Customer } from '../interfaces/customer';

@Component({
  selector: 'customerform',
  templateUrl: './customer-form.component.html',
  styleUrls: ['./customer-form.component.css']
})
export class CustomerFormComponent implements OnInit {

  @Input() name: string;
  @Input() years: number;
  @Input() income: number;
  @Input() id: string;

Answer №1

For a simple solution, consider implementing an event for calculation when needed. Utilizing the blur event can be effective.

// Incorporate this code into your HTML file
<mat-card>
    <h1>Add Customer</h1>
    <form #customerForm="ngForm">
        <mat-form-field>
                <input 
                    matInput placeholder="Education years"
                    [(ngModel)] = "years"
                    name = "years"
                    (blur)="blurEvent($event)   // Add this event in HTML
                    required="required">

                // Enhance user experience with error message styling
                <small *ngIf="blurEventError" style="'color': red">
                     Value should be between 0 and 24
                 </small>

        </mat-form-field>
    </form>
    </mat-card>

// Modify component.ts file to include:
blurEventError: boolean = false;

blurEvent(event) {
  if (event && event.target.value) {
     if (
         customerForm.controls.years.value < 0 ||
         customerForm.controls.years.value > 24
     ) {
         this.blurEventError = true;
     } 
  }
}

If the above method is unsuccessful, exploring keypress / keyup / keydown events may provide an alternative solution!

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

Stepping up the Angular AuthGuard game: Harnessing CanMatchFn and CanActivateFn for ultimate security (Class Guards make way for Functional Guards)

I have developed an Angular AuthGuard component as shown below: @Injectable({ providedIn: 'root', }) export class AuthGuard implements CanActivate, CanLoad { constructor(private authService: AuthService, private router: Router) {} ca ...

Comparison of env.local and String variables

I encountered an access denied error with Firebase. The issue seems to arise when I try passing the value of the "project_ID" using an environment variable in the backend's "configs.ts" file, as shown in the code snippet below: import 'firebase/f ...

Polling with RxJs, handling errors, and resetting retryCount with retryWhen

I am currently working on setting up a polling strategy that functions as follows: Retrieve data from the server every X seconds If the request fails, show an error message: "Error receiving data, retry attempt N°"... And retry every X seconds for a maxi ...

Dynamically Disabling Form Control in Angular 2

There is a basic form with two form controls that initially have required validation. In addition to the form controls, there is a button in the template. When this button is clicked, it triggers a change in the behavior of the form group. Both form contr ...

Having trouble retrieving information from Vuex store in Vue component when using TypeScript

I'm facing an issue with fetching data in my Vue component using Typescript. Upon logging in, I trigger an API call to retrieve data. Once the data is received, I store it using a Vuex module. @Action async getData(): Promise<TODO> { return ne ...

Implementing PHP code to prevent the submission of forms with invalid inputs

When working on a form validation process in PHP, I encountered a challenge in preventing the form from being submitted to the database when there are errors in the input fields. While I was able to display error messages for invalid inputs upon submitti ...

Can we expect Karma to receive updates for upcoming versions of Angular and Jasmine?

We recently attempted to upgrade our company's Angular module, which required updating dependencies as well. Upon upgrading to the latest versions, we encountered an issue with the Jasmine-karma-HTML-Reporter due to its reliance on Jasmine-core 4.x.x ...

Determine the data type of the property in an object that needs to be provided as an argument to a

I am currently in the process of creating a function that can take in an object with a specific data type, as well as a function that acts on that data type as its argument. const analyze = < Info extends object, F extends {initialize: Info; display ...

Creating a single page application in Angular2+ using JSON data

I am looking to create an Angular JS application using the provided JSON structure: { name: 'App Name', pages: [ { name: 'Home', url: '/', layout: { type:'HTMLElement' tag:'div ...

Tips for choosing the correct type of object to use for styling in Vue/Typescript: { }

This is how I implement styling in my Vue TypeScript project. private styleTableObject: CSSStyleSheet = { width: '100%', height: '76%' } I am being forced to use the any type. private styleTableObject: any = { ...

Implementing Data Binding with Ajax Responses in Angular 2 TypeScript Using the FetchApi Method

I am working on my first angular2 application with typescript. I have successfully fetched results using fetchApi but I am struggling to display them in the views. Can someone please guide me on how to present my data in the views? Thank you. App.componen ...

Exploring the mocking of document,hidden using Jasmine

Struggling to simulate document.hidden in an angular unit test, but facing issues. Tried the following solutions: spyOn(Document.prototype, <any>'hidden').and.returnValue(true); spyOn(Document, <any>'hidden').and.ret ...

Display the HTML tag inside a cell of a mat-table

I am currently exploring options to display an HTML tag within a cell of a mat-table in Angular. My goal is to show a colored circle next to the cell value. I have searched online for solutions, but haven't found one that works. If anyone has any insi ...

What could be causing my Jasmine test to not run the application code within a for loop?

Imagine having a straightforward function that includes a for statement: public loadImages(images): void { for (let image of images) { this.imageLoader.load(image['url']); } } When attempting to spy on imageLoader.load, the test ...

What is the best way to determine which component/service is triggering a method within an Angular 2 or 4 service?

Is there a way to determine which component or service is triggering the method of a specific service, without the need to pass additional parameters? This information must be identified directly within the service. If you have any insights on how this c ...

Add a class to a particular element within an ngFor loop

I wrote a loop that creates names along with icons. My goal is to make the icon appear only when it is hovered over. <div class="elm" *ngFor="let element of callWorkflowData?.jobsList"> <mat-card (mouseover)="hover=true" (mouseleave)="hover= ...

Utilizing Angular 2 for Integration of Google Calendar API

I recently attempted to integrate the Google Calendar API with Angular 2 in order to display upcoming events on a web application I am developing. Following the Google Calendar JavaScript quick-start tutorial, I successfully managed to set up the API, inse ...

The Postman application functions properly even though Unsupported Media Type 415 error occurred

Once a user has registered, they will receive a unique link containing their userId and a token. When the user clicks on this link, an Angular project will open and extract the userId and token from the link. This information is then sent via a post method ...

Setting up the Angular 2 router to function from the /src subfolder

My goal is to create two separate subfolders within my project: src and dist. Here are the key elements of my application: root folder: C:\Server\htdocs\ app folder: C:\Server\htdocs\src index.html contains <base href="/ ...

Encountered an issue in Angular 2 when the property 'then' was not found on type 'Subscription'

I have been attempting to call a service from my login.ts file but I am encountering various errors. Here is the code snippet in question: login.ts import { Component } from '@angular/core'; import { Auth, User } from '@ionic/cloud-angular ...