import {AfterViewInit, Component, ElementRef, OnInit, ViewChild, ViewEncapsulation} from '@angular/core'; import {FieldType} from '@ngx-formly/material'; @Component({ selector: 'jhi-phone-number', templateUrl: './phone-number.component.html', styleUrls: ['./phone-number.component.scss'], encapsulation: ViewEncapsulation.None }) export class PhoneNumberComponent extends FieldType implements OnInit, AfterViewInit { maxLength = 14; @ViewChild('inputPhone') inputPhoneField: ElementRef; constructor() { super(); } ngOnInit(): void { this.field.formControl.setValue(this.field.formControl.value ? this.field.formControl.value : null); } ngAfterViewInit() { super.ngAfterViewInit(); if (this.inputPhoneField.nativeElement.value.startsWith('+')) { this.inputPhoneField.nativeElement.value = this.formatValueWithIndicatif(this.inputPhoneField.nativeElement.value); } else { this.inputPhoneField.nativeElement.value = this.formatValueWithoutIndicatif(this.inputPhoneField.nativeElement.value); } } formatPhoneNumber(e: any): void { const value = e.target.value; if (value.startsWith('+')) { e.target.value = this.formatValueWithIndicatif(value); } else { e.target.value = this.formatValueWithoutIndicatif(value); } this.model[this.key] = this.clearValue(value); this.model['insured_identity_mobile'] = this.model[this.key]; this.validFormat(); } validFormat() { if (!/(^(?:\+)([0-9]{11,14}))|(^(?:0)([0-9]{9}))/.test(this.model[this.key])) { this.field.formControl.setErrors({format: {message: `\"${this.inputPhoneField.nativeElement.value}\" n\'est pas un numéro de téléphone valide (Exemple: 0601020304 ou +33601020304)`}}); } else { this.field.formControl.setErrors(null); } } formatValueWithoutIndicatif(value): string { this.maxLength = 14; const ele = this.clearValue(value); //Suppression des caractères en trop return ele.match(/.{1,2}/g).join('.'); } formatValueWithIndicatif(value): string { this.maxLength = 15; const ele = this.clearValue(value); //Suppression des caractères en trop return ele.match(/.{1,3}/g).join('.'); } clearValue(value: any): string { return value.split(' ').join('').split('.').join(''); } }