javascript – Angular2+ ngx-mask erasing value in dynamic mask exchange

Question:

I have a document field where the value can be CPF or CNPJ.

<label for="cnpj" class="label-control">
    <select class="labelSelect" name="tipoDoc" id="tipoDoc" [(ngModel)]="tipoDoc">
       <option value="1">CPF</option>
       <option value="2">CNPJ</option>
    </select>:
</label>
<input type="text" class="form-control form-control-sm" id="cnpj" name="cnpj" [mask]="cpfCnpjMask()" [(ngModel)]="cliente.cnpj">

Use a function to change the mask dynamically depending on the type of field to be used.

cpfCnpjMask(){

  if(this.tipoDoc==1){
    return "000.000.000-00";
  }

  return "00.000.000/0000-00";
}

On the insert screen it works normally, because when I change the field type it changes the mask and everything works out. Even if it has already entered value.

The problem happens in the edit screen that when it pulls the data from the api it erases the content if the value that is returned is CPF. With CNPJ it works normal.

Because the implementation is done after there is already data in the DB, which was previously recorded with dots, dashes and slashes due to a file import, then it was necessary to clean the returned content leaving only numbers and then perform the verification that doc type is based on the amount of characters and thus effect the mask change.

this.clienteService.edit(id).subscribe((data) => {
        this.cliente = data['result'];

        // limpa o campo pegando somente os numeros
        let cnpj = Utils.onlyNumbers(this.cliente.cnpj);

        // verifica a qtd de caracteres para determinar se é cpf ou cnpj
        if(cnpj.length === 11){
          // define o tipo de doc como cpf o que aciona a troca da mascara automaticamente
          this.tipoDoc = 1;
        }

        //atribui o cnpj limpo
        this.cliente.cnpj = cnpj;
        // no console log mostra somente os numeros sem problemas
        console.log(this.cliente.cnpj);            

 });

In the input the field is empty when it is CPF.

If I start typing in the field it normally accepts the CPF mask. But for some reason he can't assign the value. It actually assigns and seems to erase later. I can't understand why.

Answer:

Depending on your ngx-mask version, you can use "CPF_CNPJ" as a mask, and ngx-mask does the job for you.

<input type="text"
  ... 
 [mask]="CPF_CNPJ"
 [(ngModel)]="cliente.cnpj">

source: https://www.npmjs.com/package/ngx-mask#cpf_cnpj-valid-mask

Scroll to Top