Mascara CPF/CNPJ ANGULAR 8 NG-MASK

Asked

Viewed 15,990 times

7

I have a Component where I need the input to have the mask for Cpf or cnpj according to the data entry. I am using ng-Mask, but my validation for the mask is only working for the first validation. Below is the code. module ts.

import { NgxMaskModule } from 'ngx-mask';

@NgModule({
    declarations: [ .... ], 
    imports: [
        //outros imports
        NgxMaskModule.forRoot(),

    ],

In my Component.ts I am thus using the method.

@Component({
  selector: 'app-dados-bancarios-professor',
  templateUrl: './dados-bancarios.component.html',
  styleUrls: ['./dados-bancarios.component.scss']
})

//regras de negócio do component
  mask:string;

  cpfcnpjmask() {
    const value = this.dadosBancariosForm.get('cpf_cnpj').value;
    console.log(value, value.length,this.dadosBancariosForm)
    if(value.length <= 14) {
      this.mask = '00.000.000/0000-00'
    }
    else {
      this.mask = '00.000.0000-00'
    }
  }

And why I use the mask as follows in my Component.html


 <label class="control-label">CPF/CNPJ<span class="text-danger">*</span></label>
 <input type="text" class="form-control form-control-sm" formControlName="cpf_cnpj" [mask]="mask" (keyup)="cpfcnpjmask($event)">

It turns out that he makes the first bind, but does not get to execute the second mask according to what is inserted by the user. Would anyone know how to resolve this impasse?

  • 2

    Try to create a stackblitz of the problem, so I saw the length will never be greater than 14, it should not be the contrary?

  • I discovered that the Ionic brmasker lib has the masks and rotates normally at angle 8

3 answers

1

In angular version 8 o ngx-mask does not have the implamentation of CpfCnpj dynamically, only from version 9 of Angular and using the version 9.1.2 of ngx-mask to solve this problem.

For those who want to follow what was discussed and made follow the links here and here.

And according to the documentation itself, this is the form that should be used:

<input mask="CPF_CNPJ" />

Or

<input mask="000.000.000-00||00.000.000/0000-00" />

In your case, it would look like this:

<input type="text" class="form-control form-control-sm" formControlName="cpf_cnpj" mask="CPF_CNPJ">

0

I used the ngx-Mask

Component.html

<input matInput type="text" [mask]="getCpfCnpjMask()" formControlName="cpf_cnpj"
[(ngModel)]="cpf_cnpj" placeholder="Digite o CPF ou CNPJ" required>

Component.

isCPF(): boolean{
   return this.cpf_cnpj == null ? true : this.cpf_cnpj.length < 12 ? true : false;
}

getCpfCnpjMask(): string{
   return this.isCPF() ? '000.000.000-009' : '00.000.000/0000-00';
}

0

Browser other questions tagged

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