libs/core/dynamic-form/phone-input/src/phone-input.component.ts

Extends

DfBaseComponent<DfPhoneInputConfig>

Implements

OnInit

Metadata

Relationships

Index

Properties
Inputs
Outputs

Constructor

constructor()

Inputs

control
Type : UntypedFormControl
Default value : new UntypedFormControl()
Inherited from DfBaseComponent
config
Type : C
Required :  true
Inherited from DfBaseComponent

The configuration object for this formfield.

Note that derived formfield components should extend the DfBaseConfig config interface as needed and expose that their own config interface.

formAclPath
Type : string
Inherited from DfBaseComponent
isAclHandled
Type : boolean
Default value : false
Inherited from DfBaseComponent
isRetailChannel
Type : boolean
Inherited from DfBaseComponent
validationConfigs
Type : ValidationConfig[] | undefined
Inherited from DfBaseComponent

Outputs

formEvent
Type : DfEventPayload
Inherited from DfBaseComponent

Emits when events associated to the form control happen.

The emitted object contains the data necessary to uniquely identify the event (field id and event type). It also contains the event data.

Properties

componentOrControlInitFinished
Type : unknown
Default value : new ReplaySubject<AbstractControl | undefined>(1)
Inherited from DfBaseComponent

This ReplaySubject is provided to emit the control once it is initialized.

errorMessages
Type : WritableSignal<Observable[]>
Default value : signal([])
Inherited from DfBaseComponent

The resolved validation error messages for the current control state.

Readonly nxErrorAppearance
Type : ErrorStyleType
Default value : inject(ERROR_DEFAULT_OPTIONS, { optional: true })?.appearance || (inject<CHANNEL>(CHANNEL_TOKEN) === CHANNEL.EXPERT ? 'text' : 'message')
Inherited from DfBaseComponent
import { NxFormfieldModule } from '@allianz/ng-aquila/formfield';
import { NxPhoneInputModule } from '@allianz/ng-aquila/phone-input';
import { LOCALE_RUNTIME_TOKEN, NormalizeUrlModule, ValidationConfig } from '@allianz/taly-core';
import {
  DfBaseComponent,
  DfBaseModule,
  DfInfoIconComponent
} from '@allianz/taly-core/dynamic-form';
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  inject,
  input,
  LOCALE_ID,
  OnInit,
  signal,
  WritableSignal
} from '@angular/core';
import {
  AbstractControl,
  ReactiveFormsModule,
  UntypedFormControl,
  ValidatorFn
} from '@angular/forms';
import {
  GetNameOptions,
  getNames,
  LocalizedCountryNames,
  registerLocale
} from 'i18n-iso-countries';
import { parsePhoneNumber } from 'libphonenumber-js/max';
import { DfPhoneInputConfig } from './phone-input.model';
import { importIsoCountryLocaleData } from './iso-countries-mapper';

@Component({
  selector: 'df-phone-input',
  templateUrl: './phone-input.component.html',
  styleUrls: ['./phone-input.component.scss'],
  imports: [
    ReactiveFormsModule,
    DfBaseModule,
    DfInfoIconComponent,
    NxFormfieldModule,
    NxPhoneInputModule,
    NormalizeUrlModule
  ],
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DfPhoneInputComponent extends DfBaseComponent<DfPhoneInputConfig> implements OnInit {
  override control = input<UntypedFormControl>(new UntypedFormControl());

  protected countryNames: WritableSignal<LocalizedCountryNames<GetNameOptions>> = signal({});
  protected readonly selectedCountryCode = computed(() => this.config().countryCode || '');

  private currentLocale: string;

  private localeId = inject(LOCALE_ID);
  private runtimeLocale = inject(LOCALE_RUNTIME_TOKEN, { optional: true });

  private static readonly PHONE_VALIDATOR: ValidatorFn = (control: AbstractControl) => {
    const value = control.value;
    if (!value) return null;
    let isValid;
    try {
      // "extract: false" means strict parsing is applied.
      // No extra characters are allowed at the beginning or end of the phone number
      const parsedPhoneNumber = parsePhoneNumber(value, { extract: false });
      isValid = parsedPhoneNumber.isValid();
    } catch {
      isValid = false;
    }
    return isValid ? null : { invalidPhoneNumber: true };
  };

  constructor() {
    super();

    this.currentLocale = this.normalizeLocale(this.localeId);

    effect(() => {
      if (!this.runtimeLocale?.()) {
        return;
      }

      const newLocale = this.normalizeLocale(this.runtimeLocale());
      if (this.currentLocale !== newLocale) {
        this.currentLocale = newLocale;
        this.loadLocale(this.currentLocale);
      }
    });

    this.enrichedValidationConfigs = computed(() => {
      const baseValidations = this.validationConfigs() || [];

      return [
        ...baseValidations,
        {
          validatorName: 'invalidPhoneNumber',
          errorMessage: this.config().errorMessage || 'Invalid phone number'
        } as ValidationConfig
      ];
    });
  }

  override async ngOnInit(): Promise<void> {
    super.ngOnInit();
    this.emitFormControlEventOnValueChangesWithDebounce();
    this.control().addValidators(DfPhoneInputComponent.PHONE_VALIDATOR);
    await this.loadLocale(this.currentLocale);
  }

  private async loadLocale(locale: string): Promise<void> {
    const localeData = await importIsoCountryLocaleData(locale);
    registerLocale(localeData.default || localeData);
    this.countryNames.set(getNames(localeData.default?.locale || localeData.locale));
  }

  private normalizeLocale(locale: string): string {
    return locale.split('-')[0].toLowerCase();
  }
}
<nx-formfield [label]="config().label | interpolateFromStore | async">
  <nx-phone-input
    [attr.data-testid]="config().testId"
    [formControl]="control()"
    [placeholder]="(config().placeholder | interpolateFromStore | async) || ''"
    [countryNames]="countryNames()"
    [countryCode]="selectedCountryCode()"
    [areaCodeLabel]="config().areaCodeLabel ?? ''"
    [lineNumberLabel]="config().lineNumberLabel ?? ''"
    (blur)="emitFormEvent('onBlurEvent', control().value)"
  >
  </nx-phone-input>
  @if(config().hint) {
  <span nxFormfieldHint>
    {{ config().hint | interpolateFromStore | async }}
  </span>
  } @if(config().infoIcon){
  <df-info-icon nxFormfieldAppendix [config]="config().infoIcon"></df-info-icon>
  } @for (message$ of errorMessages(); track $index) {
  <nx-error nxFormfieldError [appearance]="nxErrorAppearance">{{ message$ | async }}</nx-error>
  }
</nx-formfield>

./phone-input.component.scss

:host {
  display: block;
}
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""