2

I have a text input field where I want to apply a custom directive so that user is allowed to only enter numbers. I have created this directive but it seems event.stopPropagation() is not working. Any suggestion?

import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[appNumbersOnly]' }) export class NumbersOnlyDirective { constructor(private _el: ElementRef) { } @HostListener('input', ['$event']) onInputChange(event) { const initalValue = this._el.nativeElement.value; this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, ''); if ( initalValue !== this._el.nativeElement.value) { event.stopPropagation(); } } } 
1

1 Answer 1

1

You can do it without directive. Only you have to do is add type="number".

<input type="number" ...> 
Sign up to request clarification or add additional context in comments.

1 Comment

But that is not the best solution. we need to know why stopPropagation is not working. If u have some other directives that allows only alphanumeric chars. So to make them working u need to fix that issue

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.