Search code examples
javascriptangulartypescriptangular9mobile-browser

Custom Directive developed in Angular 9 not working in mobiles


I have developed a custom directive in angular 9 to enter only digits and 1 decimal. The directive works flawlessly in desktop but not in mobiles (as if the directive is not even present in the input field). I used keydown event as the host. Is this an issue in Angular side? Any suggestions or existing posts that I need to refer.

EDIT

@Directive({ 
    selector: 'input[allowCurr]',
    host: { '(keydown)': 'allowND($event)' } 
})
export class AllowCurrDirective { 
    @Input() allowCurr: string;
     /* Rest of my Logic here */ 
} 

I added this much because I had put alert inside my allowND function, it is going inside it but event.key, that I had used to capture user key input, is coming undefined.


Solution

  • Finally I was able to solve this. I had to use event.target.value alongwith input event to meet my requirement for allowing only numbers and one decimal to be typed inside input box.

    :: Research ::

    Open this MDN URL in your smartphone browser. You can see that on input event, KeyboardEvent.data works as KeyboardEvent.key in desktop. That means you can see the key you pressed in your smartphone keyboard. (I confirmed it in W3schools try-it editor also, in my smartphone). But the thing is KeyboardEvent.data is not compatible for iPhones. That means, I can neither use event.key nor event.data. Input event is not cancellable (that means event.preventDefault() wont work either) so whatever you type if it doesn't get through the condition, the input value should be:

    let targetVal = event.target.value;
    event.target.value = targetVal.substring(0, targetVal.length -1);