Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CPF / CNPJ Issue
<ion-item>
<ion-label floating>Tipo de Pessoa</ion-label>
<ion-select [formControl]="dataForm.controls['tipo_pessoa']" (ionChange)="selectPfOrPj()">
<ion-option [value]="PF">PF</ion-option>
<ion-option [value]="PJ">PJ</ion-option>
</ion-select>
</ion-item>
<ion-item>
<ion-label floating>CPF</ion-label>
<ion-input type="tel" limit="14" pattern="\d*" mask="***.***.***-**" [formControl]="dataForm.controls['cpf']" (ionChange)="checkCpf()" [disableControl]="!isPF"></ion-input>
</ion-item>
<div *ngIf="isPF && dataForm.controls.cpf.touched" class="validator-error">
Informe o CPF
</div>
<ion-item>
<ion-label floating>CNPJ</ion-label>
<ion-input type="tel" limit="18" pattern="\d*" mask="**.***.***/****-**" [formControl]="dataForm.controls['cnpj']" (ionChange)="checkCnpj()" [disableControl]="!isPJ"></ion-input>
</ion-item>
<div *ngIf="isPJ && dataForm.controls.cnpj.touched" class="validator-error">
Informe o CNPJ
</div>
isPF : boolean = false;
isPJ : boolean = false;
selectPfOrPj() {
if (this.dataForm.controls['tipo_pessoa'].value == 'PF') {
this.isPF = true;
this.isPJ = false;
this.dataForm.controls['cpf'].setValidators([Validators.required]);
this.dataForm.controls['cnpj'].setErrors(null);
this.dataForm.controls['cnpj'].markAsUntouched();
} else if (this.dataForm.controls['tipo_pessoa'].value == 'PJ') {
this.isPF = false;
this.isPJ = true;
this.dataForm.controls['cnpj'].setValidators([Validators.required]);
this.dataForm.controls['cpf'].setErrors(null);
this.dataForm.controls['cpf'].markAsUntouched();
}
}
checkCpf() {
if (this.dataForm.controls['cpf'].value.length > 0) {
this.dataForm.controls['cpf'].setErrors(null);
}
}
checkCnpj() {
if (this.dataForm.controls['cnpj'].value.length > 0) {
this.dataForm.controls['cnpj'].setErrors(null);
}
}
import { Directive, Input } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[disableControl]'
})
export class DisableControl {
@Input() set disableControl( condition : boolean ) {
const action = condition ? 'disable' : 'enable';
this.ngControl.control[action]();
}
constructor( private ngControl : NgControl ) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment