ionic 2 angular maxlength issue in android devices

In Ionic 2, the maxlength property is working as expected in ios devices and on some android devices. But it doesn't work if the device is using native keyboard. This is the custom directive to make it work in all the devices. In ios, it uses the native maxlength property and in android, it uses custom maxlength property.

import { Directive, EventEmitter, HostListener, Input, Output } from '@angular/core';
import { Platform } from "ionic-angular";

    selector: '[cMaxLength]'
export class MaxLengthDirective {

  @Input('cMaxLength') cMaxLength:any;
  @Output() ngModelChange:EventEmitter = new EventEmitter();

  constructor(public platform: Platform) {

  //keypress event doesn't work in ionic android. the keydown event will work but the value doesn't effect until this event has finished. hence using keyup event. 
  @HostListener('keyup',['$event']) onKeyup(event) {
    const element = as HTMLInputElement;
    const limit = this.cMaxLength;
    if ('android')) {
      const value = element.value.substr(0, limit);
      if (value.length <= limit) {
        element.value = value;
      } else {
        element.value = value.substr(0, limit-1);

  @HostListener('focus',['$event']) onFocus(event) {
    const element = as HTMLInputElement;
    if (!'android')) {
      element.setAttribute('maxlength', this.cMaxLength)

Usage: Include the above directive in shared module to make use of this in entire application.

Categories: ,