1

I have a Angular 4.3 application where i have a contenteditable

I need to validate input before it can be it can be reflected in UI (in this instance only numbers upto three charecters can be typed )

In desktop browsers this accomplished using (keydown) event and returning false on invalid input

But in mobile browser(Android Chrome) both keydown and keypress events are not triggered consistently, instead input Event is fired.

but using InputEvent i cannot prevent modifying data on invalid input

Example HTML template

<p contenteditable=true (keydown)="onKeyDown($event)" (input)="onInput($event)"></p>

and component code is

public onKeyDown($event:KeyboardEvent){ // works
    if(invalidInput){
        return false;
    }
    return true;
}
public onInput($event:InputEvent){ // does'nt works
    if(invalidInput){
        $event.preventDefault();
        return false;
    }
    return true;
}

PS: Is there a way to trigger numberpad keyboard for input with contenteditable

AbdulKareem
  • 1,199
  • 8
  • 24

1 Answers1

1

You can make it work with input.

HTML:

...
<div #myEditable contentEditable (input)="valueChanged($event.target.innerText)"></div>
...

TypeScript:

.....
if(value.length>20){ //for example
   this.name = this.name.slice(0,20);
   this.validationError=true;
   this.myEditable.nativeElement.innerText = this.name;
....

It's not very neat I think to keep that last part in the component, so you can maybe move to a directive.

Working demo

Vega
  • 27,856
  • 27
  • 95
  • 103
  • Thanks for answer, I want to avoid this solution as cursor can be at any point, then doing validation will be a mess after modifification – AbdulKareem Sep 07 '17 at 05:22
  • What do you think of this solution : https://stackoverflow.com/a/41034697/5468463 – Vega Sep 07 '17 at 05:45
  • 1
    Do you have any constraint to use contenteditable? Because with

    and and it would be easier. If you are interested, I could post a snippet

    – Vega Sep 07 '17 at 05:47
  • thanks again , I think i will go with this logic only, along with https://stackoverflow.com/a/41034697/5468463 Solution will be complex but will work i think – AbdulKareem Sep 07 '17 at 06:50