Search code examples
androidangulargoogle-chromecontenteditable

Chrome Android Angular Contenteditable validating input before modification


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


Solution

  • 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