webcat12345 / ngx-intl-tel-input

Phone number input field to support international numbers, Angular
MIT License
213 stars 333 forks source link

Events binding not working on component switching #490

Open nizalsha opened 1 year ago

nizalsha commented 1 year ago

I have multiple components with ngx-intl-tel-input

when I first load a component everything works fine all the validations and events are running okay and my component is like this

`import { AfterViewInit, Component, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { Resources } from '../resources/resources';
import { md5 } from 'pure-md5';
import { DbservicesService } from '../services/data/dbservices.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { Router } from '@angular/router';
import { AdminHomeComponent } from '../admin-home/admin-home.component';
import { HotToastService } from '@ngneat/hot-toast';

import intlTelInput from 'intl-tel-input';
import { ToastService } from '../services/toast/toast.service';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { SearchCountryField, CountryISO, PhoneNumberFormat } from 'ngx-intl-tel-input-gg';

@Component({
  selector: 'app-manager-create',
  templateUrl: './manager-create.component.html',
  styleUrls: ['./manager-create.component.css']
})
export class ManagerCreateComponent implements OnInit, AfterViewInit, OnDestroy {

  regexMail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

  firstName: any;
  lastName: any;
  username: any;
  password: any;
  confirmPassword: any;
  isSuperAdmin!: boolean;
  phone: any;
  email: any;
  countryDialCode: any;

  managers: any = [];
  managerList: any = [];
  centerLists: any = [];
  selectedCenters: any = [];

  invalid: boolean = false;
  noUserFound: boolean = false;
  disableBtn: boolean = false;
  alreadyExist: boolean = false;
  isSuperAdminLogedIn: boolean = false;
  invalidLength:boolean = false;
  invalidNumber:boolean = false;
  validNumber: boolean = false;

  selectedManager: any;
  assignedCenters: any = [];
  selectedCenter: any;
  notAssignedCenterList: any = [];

  bgColor: any;
  textColor: any;
  provider: any;

  toastOpen: any;

  private phoneInput!: HTMLInputElement;
  private onFocusHandler!: () => void;
  private onBlurHandler!: () => void;
  phoneInitializer: any;

  @ViewChild ('template', {static: true})
  template!: TemplateRef<any>;
  neverShowToast: boolean = false;

  separateDialCode = true;
    SearchCountryField = SearchCountryField;
    CountryISO = CountryISO;
  selectedCountry: string = '';
  selectedCountryISO!: CountryISO;
  PhoneNumberFormat = PhoneNumberFormat;
    preferredCountries: CountryISO[] = [CountryISO.India, CountryISO.UnitedArabEmirates];
  phoneForm = new FormGroup({
        phone: new FormControl(undefined,  [Validators.required])
    });

  constructor(private db: DbservicesService, private modalService: NgbModal, private router: Router, private toast: ToastService) {

  }

  ngOnInit(): void {
    // const url = this.router.url.toString().split(';')[0];
    // localStorage['setItem']('lastRoute', url);
    // AdminHomeComponent.updateCurrentUrl(url);
    this.isSuperAdminLogedIn = Resources.loged_manager_details.isSuperAdmin;
    this.provider = Resources.serviceProvider;
    this.selectedCountryISO = Resources.providerDetails.country_code;
   //  this.getManagers(this.provider);
   //  this.getCenters(localStorage.getItem('company_id'));
    if(!Resources.themePrimaryColor){
      this.bgColor = Resources.defaultPrimaryColor;
      this.textColor = Resources.getContrastColor(Resources.defaultPrimaryColor);
    } else {
      this.bgColor = Resources.providerDetails.themeprimarycolor;
      this.textColor = Resources.getContrastColor(Resources.providerDetails.themeprimarycolor);
    }

    this.toast.openToastMessage(this.template, 'managercreate');

    console.log(this.phoneInput)
  }

  updatePhone(event: any){
    console.log(event);
    if(!this.phoneForm.invalid){
      this.invalidNumber = false;
      this.validNumber = true;
      const number = event?.number.replace(/\s/g, '');
      const dialCode = event?.dialCode;
      this.countryDialCode = dialCode;
      Resources.country_dial_code = dialCode;
      this.phone = parseInt(number);
    } else {
      this.invalidNumber = true;
      this.validNumber = false;
    }
  }

  neverShowToastAgain(){
    const neverShowToastAgain = this.neverShowToast;
    this.toast.stopShowingToast(neverShowToastAgain);
  }

  ngAfterViewInit():void{
    this.phoneInput = document.getElementById('phone') as HTMLInputElement;
    this.onFocusHandler = () => { this.onFocus(); };
    this.onBlurHandler = () => { this.onBlur(); };
    this.phoneInput.addEventListener('focus', this.onFocusHandler);
    this.phoneInput.addEventListener('blur', this.onBlurHandler);
    setTimeout(() => {
      if(!this.phoneInput.value){
        this.invalidNumber = true;
        this.validNumber = false;
      }
      const url = this.router.url.toString().split(';')[0];
      localStorage['setItem']('lastRoute', url);
      AdminHomeComponent.updateCurrentUrl(url);
    });
  }

  onFocus() {
    // this.phoneInput.classList.add('focus');
  }

  onBlur() {
    // this.phoneInput.classList.remove('focus');
    const number = (document.getElementById('phone') as HTMLInputElement).value;
    console.log(number);
    console.log(this.phoneForm.invalid);
    if(this.phoneForm.invalid){
      this.invalidNumber = true;
      this.validNumber = false;
    } else {
      this.invalidNumber = false;
      this.validNumber = true;
    }
  }

  ngOnDestroy():void {
    this.toast.closeToast();
    if(this.phoneInitializer){
      this.phoneInitializer.destroy();
    }
    if(this.phoneForm){
      this.phoneForm.reset({phone: null});
    }
    if(this.phoneInput){
      this.phoneInput.removeEventListener('focus', this.onFocus);
      this.phoneInput.removeEventListener('blur', this.onBlur);
    }
  }
}
`

But when switch to another component having a phone input the validators are not working there and when i come back to the previous page the validators are stopped working. I really dont know what is happening here. Any help ?