Implement a directive in Angular 2 using typescript to validate user input

I am currently developing a project in Angular2 using Typescript. My goal is to create a validation directive that can take the value from an HTML tag, determine its type based on the input, and then return a boolean response.

The directive I have written looks like this:

import { Directive, ElementRef, HostListener, Input, Output } from '@angular/core';

@Directive({
    selector: '[validate]'
})

export class Validation{
    @Input('validate') validateType: string;
    @Input() validateValue: string;

    @Output() status:boolean;
    
    constructor(private el : ElementRef){
    }

    @HostListener('keyup') OnKeyUp(){
       if(this.validateType === "number")
        {
            var isNumeric = /^[-+]?(\d+|\d+\.\d*|\d*\.\d+)$/;
            this.status = isNumeric.test(this.validateValue);
        }
    }
}

In my app.module.ts file, I registered the directive as follows:

import { Validation}            from './validation-directive/validation.directive';
.
.
.
@NgModule({
.
.,
  declarations: [
     Validation
  ],
})

The corresponding HTML code for implementing this directive is:

<input #validateNumber [validate]="number" validationValue="validateNumber.value" />
<span>result is: </span>

My issue is that the code is not functioning properly and the directive does not seem to be working, even though there are no errors being displayed. What could be wrong with my code? And how can I display the output in the `span` element?

Your help is greatly appreciated.

Answer №1

Check it out on Plunker

Utilize the exportAs attribute to access your directive properties within your template

HTML:

 <input validate="number"  #validator="validator"  />

    <span>The result is: {{ validator.status }}</span> 

TypeScript:

    import { Directive,Input,ElementRef,HostListener} from '@angular/core';

    @Directive({
       selector: '[validate]',
       exportAs: "validator"
    })
    export class Validation{
        @Input('validate') validateType: string;
        status : boolean;

        constructor(private el : ElementRef){
        }

        @HostListener('keyup') OnKeyUp(){

           if(this.validateType === "number")
            {
                let value = this.el.nativeElement.value;
                let isNumeric = /^[-+]?(\d+|\d+\.\d*|\d*\.\d+)$/;
                this.status = isNumeric.test(value);
            }

        }
    }

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

Tips for implementing this feature in Angular to translate an object into multiple languages

When I previously used this service in another question: import { Injectable } from '@angular/core'; import { BehaviorSubject, fromEvent, interval, merge, Observable } from 'rxjs'; import { TranslateService } from '@ngx-tr ...

Troubleshooting: Angular 2 property binding animations not functioning as expected

I'm attempting to create a fade-in animation for a div element. Here is the code snippet: import { Component, trigger, state, style, transition, animate, keyframes, group } from '@angular/core'; @Component( ...

Challenges with using React Component as node package hooks

I am currently working on a React component that I plan to turn into an npm package for easy import into different React projects. However, I have encountered an issue with the "useRef" hook. Here is an overview of my package.json: { "name": "@mperudire ...

The concept of nesting partial types in Typescript

Struggling to type partial objects from GraphQL queries, especially with an object that looks like this... // TypeScript types interface Foo { bar: Bar } interface Bar { a: number, b: number } // GraphQL query foo { bar { a // 'b&a ...

Properly incorporating life cycle hooks into an abstract base component in Angular: A comprehensive guide

I have a unique abstract base component that includes life cycle hooks: export abstract class BaseComponent implements OnChanges, OnInit { ngOnChanges(changes: SimpleChanges): void { … } ngOnInit() { … } } Now, let's discuss a ...

Adjust the width of the div by dragging one of its edges

My web application, which is built using Angular 2, features a two-panel layout. I am looking to implement the functionality to resize both panels by selecting either the right edge of the left panel or the left edge of the right panel. If you have any su ...

The webpack task has failed because it cannot read the property 'forEach' of an undefined object

Encountering errors during the build process of a jhipster project when running ./gradlew in the project's directory. Starting a Gradle Daemon (subsequent builds will be faster) > Task :webpack > <a href="/cdn-cgi/l/email-protection" class ...

"What is the best method to retrieve the current router URL on Angular prior to the beforeunload

I have been facing a challenge in my Angular application where I need to store the current router URL when the user clicks on browser refresh. This is necessary due to our Single Sign-On (SSO) mechanism, which redirects users only to the root page. To over ...

Convert the string by removing the comma after submitting a form

Looking for a JavaScript component to format the number field on my website form. I want the number to display with commas as the user types, like "100,000". However, when the user submits the form, I need it to be saved as a string without commas, like "1 ...

The production build failed following the upgrade to ag-grid version 22.1.1

Since version 18, I have been utilizing ag-grid, and I am currently on version 20.0.0. I am now in the process of upgrading to the latest version - 22.1.1. After addressing warnings/errors caused by breaking changes, everything seems to be working fine, ...

Launching the VS Code debugger feels like inviting my web app to a party

Recently, I've noticed an issue while debugging my vs code. It appears that the debugger hosts my app without me even running npm start. This behavior allows me to access my app in Chrome without initiating npm start. Normally, my app runs on port 300 ...

The underscore symbol, also known as '_', is defined locally within this context, but it is not made available for export

Lately, I've been attempting to incorporate the UNDERSCORE library into my angular 8 application. However, I keep encountering a warning message that says, declares '_' locally, but it is not exported when trying to utilize it in the newly c ...

`Optimizing bundle size in Webpack using braintree-web integration with TypeScript`

When utilizing braintree-web 3.61.0 with Vue.js 2.6.11 and TypeScript 3.8.3, I organize the necessary components of braintree-web into a service in this manner: import { client, hostedFields, applePay } from 'braintree-web'; export default { cli ...

Switch things up in the mat-tree angular

Is there a way to change the orientation of a mat-tree-node to "RTL" and adjust the padding to be on the right side? <mat-tree [dataSource]="dataSource" [treeControl]="treeControl"> <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggl ...

Retrieving the current user in NestJS on a specific route without using an AuthGuard

I am utilizing NestJS with Passport and JWT strategy to authenticate users. My goal is to retrieve the current user on certain requests. To achieve this, I have created a custom decorator: import { createParamDecorator, ExecutionContext } from '@nestj ...

Using TypeScript to test a Vue3 component that includes a slot with Cypress

I'm currently facing challenges setting up a new project. The technologies I am using include Vue3, TypeScript, and Cypress. It seems like the problem lies within the TypeScript configuration. Below is a Minimal Working Example (MWE) of my setup. Any ...

Previewing a webpage on npm using Angular

I am currently attempting to integrate the following package into my project npm install webpage-preview. However, I am unsure of where to place this code as the webpagePreview is showing as undefined. Could it be that this is exclusively for AngularJS o ...

The Function-supported Operation is having trouble implementing a modification related to Geohash/Geopoint - the Object Type requires a String format

Summary: My function-based Action that tries to set a GeoPoint as a Geohash property is failing with an error suggesting it was anticipating a string. I have an Object Type with a String property that has been designated as a Geohash in the property edito ...

The Angular 2 application encountered issues following an upgrade to version 2.0.0-rc.1

I recently attempted to update my project to version 2.0.0-rc.1, but encountered this Exception that I cannot seem to resolve. After running ng serve, there are no errors reported, yet in the dist folder /vendor/@angular/router-deprecated directory exists. ...

Is it possible to perform a comprehensive text search in Mongoose using multiple criteria and connecting them with an AND operator?

Currently, I am able to smoothly perform a full text search using just one word. However, I'm facing difficulty in searching for multiple parameters or entering them at the same time. This is how my function looks like: export const searching = ( ...