Ionic Directive for numerical masking is not accessed from other pages

Asked

Viewed 106 times

1

I created a project with Ionic with two pages: Login and registration.

The structure is this

Estrutura

In both I tried to add a directive that creates a mask for CNPJ. Follows code of the directive

import { Directive, HostListener, Input } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

@Directive({
    selector: '[mask]',
    providers: [{
        provide: NG_VALUE_ACCESSOR,
        useExisting: MaskDirective,
        multi: true
    }]
})
export class MaskDirective implements ControlValueAccessor {

    onTouched: any;
    onChange: any;

    @Input('mask') mask: string;

    writeValue(value: any): void {
    }

    registerOnChange(fn: any): void {
        this.onChange = fn;
    }

    registerOnTouched(fn: any): void {
        this.onTouched = fn;
    }

    @HostListener('keyup', ['$event'])
    onKeyup($event: any) {
        var valor = $event.target.value.replace(/\D/g, '');
        var pad = this.mask.replace(/\D/g, '').replace(/9/g, '_');
        var valorMask = valor + pad.substring(0, pad.length - valor.length);

        // retorna caso pressionado backspace
        if ($event.keyCode === 8) {

            if (this.onChange != undefined) {
                this.onChange(valor);
            }
            return;
        }

        if (valor.length <= pad.length && this.onChange != undefined) {
            this.onChange(valor);
        }

        var valorMaskPos = 0;
        valor = '';
        for (var i = 0; i < this.mask.length; i++) {
            if (isNaN(parseInt(this.mask.charAt(i)))) {
                valor += this.mask.charAt(i);
            } else {
                valor += valorMask[valorMaskPos++];
            }
        }

        if (valor.indexOf('_') > -1) {
            valor = valor.substr(0, valor.indexOf('_'));
        }

        $event.target.value = valor;
    }

    @HostListener('blur', ['$event'])
    onBlur($event: any) {
        if ($event.target.value.length === this.mask.length) {
            return;
        }
        if (this.onChange != undefined) {
            this.onChange('');
        }
        $event.target.value = '';
    }
}

To use it would just add in the login.html

 <ion-input type="tel" maxlength="18" name="cnpj" mask="99.999.999/9999-99" [(ngModel)]="registerCredentials.cnpj" required></ion-input>

and on record

<ion-input type="tel" maxlength="18" name="cnpj" mask="99.999.999/9999-99" required></ion-input>`

Login.

import { Component } from '@angular/core';
import { IonicPage, NavController } from 'ionic-angular';
import { ServiceProvider } from '../../providers/service/service';


@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  registerCredentials: any = { cnpj: '', senha: '' };

  constructor(public navCtrl: NavController, private serviceProvider: ServiceProvider) {
  }

  public criarConta() {
    this.navCtrl.push('RegistroPage');
  }

  public login() {

    this.serviceProvider.post('autenticacao/autenticarEmpresa', { id: 1 }).subscribe(dados => {
      debugger
    });
  }

}

My app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { HttpModule } from '@angular/http';
import { MyApp } from './app.component';
import { LoginPage } from '../pages/login/login';
import { ServiceProvider } from '../providers/service/service';
import { MaskDirective } from '../directives/MaskDirective ';



@NgModule({
  declarations: [
    MyApp,
    MaskDirective,
    LoginPage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    LoginPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: ErrorHandler, useClass: IonicErrorHandler },
    ServiceProvider
  ]
})
export class AppModule { }

When I execute the code on the login page the text is formatted, but when I go to the registration page the directive is not executed. I believe it’s something with modularization, like exporting this directive to the page module.

No login.module.ts e registro.module.ts was not changed anything

How can I make this directive visible in both modules?

I also googled and saw something to make this directive a module.

If the solution is to add in a module. how do this?

Thank you.

1 answer

0

I use the ngx-Mask in my designs, it’s quite easy to use.

1-Configure it in the app.module and then the component that will use it. 2- No input, typhoon mask='(00)00000-0000'

And there you are! Any questions, just let me know.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.