Angular 6 numberonly directive not working

Viewed 12844

I have created a directive from https://www.davebennett.tech/angular-4-input-numbers-directive/ so that I can restrict users to input only digits in phone number. In src/app/app.sharerd.module.ts file, I did the below code to import the directive:

import { NumberOnlyDirective } from './number.directive';
declarations: [..., ..., NumberOnlyDirective], ...
export class SharedModule { }

Now, under /src/ folder I have created folders named modules/auth/component/.

Under auth.module.ts within the /src/auth/ folder, I have done the following:

import { NgModule } from '@angular/core';
import { SharedModule } from '../../app/app.shared.module';
...
...

Now, in the signup.html under /src/auth/component/:

<input type="text" name="phone" myNumberOnly ... > ...
...

I can still enter characters / special chars etc into the text box however, I did not see any error in console/cli.

3 Answers

When you are using custom directive/pipe in a shared module, you need to exports it also.

Basically in your tutorial, he created the directive and declared it in the app module. But in your example, you put your directive in a shared module, so you need to put your directive in the declarations bracket but also in the exports.

shared.module.ts :

@NgModule({
    /* ... */
    declarations: [YourDirective],
    exports: [YourDirective]
    /* ... */
})

Three quick directive debugging tips:

  • Put a debugger; statement inside the constructor of your directive. Then you'll know for sure when it's working and you can remove it.
  • Make sure you have selector: '[magicFeature]' and not selector: 'magicFeature'
  • Sometimes you need to restart your ng serve to make sure everything is refreshed.

Try this :

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

@Directive({
  selector: 'input[type=number], input[numbersOnly]'
})
export class NumbersOnlyInputDirective {

  constructor(private elRef: ElementRef) { }

  @HostListener('input', ['$event']) onInputChange(event) {
    const initalValue = this.elRef.nativeElement.value;
    this.elRef.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
    if ( initalValue !== this.elRef.nativeElement.value) {
      event.stopPropagation();
    }
  }

}
Related