Smokey
Smokey

Reputation: 1897

nativescript-angular - KeyboardEvent is not defined

I'm trying to create a directive which will limit the decimal points to maximum two. So when a user inputs a decimal number, he can only enter maximum two decimal points. It works in Angular but not in Nativescript Angular.

This is the directive that I created:

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

@Directive({
  selector: '[nsTwoDecimalPlaceLimit]'
})
export class TwoDecimalPlaceLimitDirective {

  private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete'];

  constructor(private el: ElementRef) {
  }

  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
    let current: string = this.el.nativeElement.value;
    const position = this.el.nativeElement.selectionStart;
    const next: string = [current.slice(0, position), event.key == 'Decimal' ? '.' : event.key, current.slice(position)].join('');
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}

And the HTML part looks like this:

    <StackLayout class="form">
        <TextField class="m-5 input input-border" hint="Disabled" nsTwoDecimalPlaceLimit>
        </TextField>
    </StackLayout>

When I run this, I get the following error:

ERROR Error: Uncaught (in promise): ReferenceError: KeyboardEvent is not defined

Here's a Playground Sample

Upvotes: 2

Views: 731

Answers (1)

Chanaka Weerasinghe
Chanaka Weerasinghe

Reputation: 5742

In goving answer

https://github.com/angular/universal/issues/830#issuecomment-345228799

you have to change in node_modules

angular-universal-starter/blob/master/server.ts

replace it

global['KeyboardEvent'] = win.Event;

check this also

Angular Universal ReferenceError - KeyboardEvent is not defined

Upvotes: 2

Related Questions