libs/core/dynamic-form/dropdown/src/dropdown.component.ts

Extends

DfBaseComponent<DfDropdownConfig>

Implements

OnInit

Metadata

Relationships

Index

Properties
Methods
Inputs
Outputs

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.

Methods

getDropDownOptions
getDropDownOptions(configValue: unknown)
Parameters :
Name Type Optional Default value
configValue unknown No this.config()

Properties

Readonly dropDownOptions$
Type : Observable<DfOptions[]>
Default value : toObservable(this.config).pipe( switchMap((configValue) => this.getDropDownOptions(configValue)), delay(0), //fix expression changed after checked tap((values) => this.syncControlWithOptions(values)), shareReplay(1) )
Readonly interpolatedDropDownOptions$
Type : Observable<DfOptions[]>
Default value : this.dropDownOptions$.pipe( switchMap((options) => this.interpolateOptions(options)) )
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 {
  DfBaseComponent,
  DfOptions,
  DfOptionsProviderService
} from '@allianz/taly-core/dynamic-form';
import { ChangeDetectionStrategy, Component, inject, input, OnInit } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
import { UntypedFormControl } from '@angular/forms';
import { combineLatest, Observable, of } from 'rxjs';
import { delay, map, shareReplay, switchMap, tap } from 'rxjs/operators';
import { DfDropdownConfig } from './dropdown.model';
import { TalyStateService } from '@allianz/taly-core';

@Component({
  selector: 'df-dropdown',
  styleUrls: ['./dropdown.component.scss'],
  templateUrl: './dropdown.component.html',
  standalone: false,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DfDropdownComponent extends DfBaseComponent<DfDropdownConfig> implements OnInit {
  private optionsProviderService = inject(DfOptionsProviderService, { optional: true });
  private talyStateService = inject(TalyStateService, { optional: true });

  override control = input<UntypedFormControl>(new UntypedFormControl());

  readonly dropDownOptions$: Observable<DfOptions[]> = toObservable(this.config).pipe(
    switchMap((configValue) => this.getDropDownOptions(configValue)),
    delay(0), //fix expression changed after checked
    tap((values) => this.syncControlWithOptions(values)),
    shareReplay(1)
  );

  readonly interpolatedDropDownOptions$: Observable<DfOptions[]> = this.dropDownOptions$.pipe(
    switchMap((options) => this.interpolateOptions(options))
  );

  override ngOnInit() {
    super.ngOnInit();
    // Validate initial options synchronously to preserve original fail-fast behavior.
    const initialOptions = this.config().options;
    if (Array.isArray(initialOptions)) {
      this.validateNoDuplicateValues(initialOptions);
    }
    this.emitFormControlEventOnValueChanges();
  }

  // TODO: Change this to be an impure pipe (There is already a ticket for that):
  getDropDownOptions(configValue = this.config()): Observable<DfOptions[]> {
    if (Array.isArray(configValue.options)) {
      this.validateNoDuplicateValues(configValue.options);
      return of(configValue.options);
    }

    if (typeof configValue.options === 'string' && this.optionsProviderService) {
      return this.optionsProviderService.getDfOptions(configValue.options).pipe(
        tap((options) => {
          this.validateNoDuplicateValues(options);
        })
      );
    }

    return of([]);
  }

  private syncControlWithOptions(values: DfOptions[]): void {
    const optionValues = values.map((option) => option.value);
    const currentValue = this.control().value;
    const configValue = this.config();

    if (configValue.autoPrefill && values.length === 1) {
      const singleValue = values[0].value;
      this.control().setValue(configValue.multiSelect ? [singleValue] : singleValue);
      return;
    }

    if (currentValue != null) {
      // To prevent invalid values in state
      if (configValue.multiSelect) {
        const isValid =
          Array.isArray(currentValue) &&
          currentValue.length > 0 &&
          currentValue.every((val) => optionValues.includes(val));
        if (!isValid) {
          this.control().setValue([]);
        }
      } else {
        if (!optionValues.includes(currentValue)) {
          this.control().setValue('');
        }
      }
    }
  }

  private interpolateOptions(options: DfOptions[]): Observable<DfOptions[]> {
    if (!options.length) return of([]);
    const talyStateService = this.talyStateService;
    if (!talyStateService) return of(options);

    return combineLatest(
      options.map((option) =>
        talyStateService
          .interpolateFromStore$(option.label)
          .pipe(map((interpolatedLabel) => ({ ...option, label: interpolatedLabel })))
      )
    );
  }

  private validateNoDuplicateValues(options: DfOptions[] | null): void {
    if (!options?.length) {
      return;
    }

    const values = options.map((opt) => opt.value);
    const uniqueValues = new Set(values);
    if (values.length !== uniqueValues.size) {
      throw new Error(
        `Dropdown "${
          this.config().id
        }" contains duplicate option values. Please check your options configuration.`
      );
    }
  }

  protected onBlur() {
    this.emitFormEvent('onBlurEvent', this.control().value);
  }
}
<nx-formfield
  [label]="config().label | interpolateFromStore | async"
  [optionalLabel]="(config().optionalLabel | interpolateFromStore | async) || ''"
>
  @if (config().inputPrefix) {
  <span nxFormfieldPrefix>
    {{ config().inputPrefix | interpolateFromStore | async }}
  </span>
  } @if (config().inputPrefix) {
  <span nxFormfieldPrefix>
    {{ config().inputPrefix | interpolateFromStore | async }}
  </span>
  } @if (config().multiSelect) {
  <nx-multi-select
    [formControl]="control()"
    [filter]="!!config().showFilter"
    [placeholder]="(config().placeholder | interpolateFromStore | async) || ''"
    (focusOut)="onBlur()"
    [attr.data-testid]="config().testId"
    [filterPlaceholder]="(config().filterPlaceholder | interpolateFromStore | async) || ''"
    [options]="(interpolatedDropDownOptions$ | async) || []"
    selectValue="value"
    selectLabel="label"
  >
  </nx-multi-select>
  } @else {
  <nx-dropdown
    [formControl]="control()"
    [showFilter]="!!config().showFilter"
    (focusOut)="onBlur()"
    [attr.data-testid]="config().testId"
    [placeholder]="(config().placeholder | interpolateFromStore | async) || ''"
    filterPlaceholder="{{ (config().filterPlaceholder | interpolateFromStore | async) || '' }}"
  >
    @if (config().clearOptionLabel && control().value) {
    <nx-dropdown-item>
      <span>{{ config().clearOptionLabel | interpolateFromStore | async }}</span>
    </nx-dropdown-item>
    } @for (optionConfig of interpolatedDropDownOptions$ | async; track optionConfig.value) {
    <nx-dropdown-item [value]="optionConfig.value" #thisInput>
      <span>{{ optionConfig.label }}</span>
    </nx-dropdown-item>
    }
  </nx-dropdown>
  } @if (config().inputSuffix) {
  <span nxFormfieldSuffix>
    {{ config().inputSuffix | interpolateFromStore | async }}
  </span>
  } @if (config().hint) {
  <span nxFormfieldHint>
    {{ config().hint | interpolateFromStore | async }}
  </span>
  } @if (config().infoIcon) {
  <df-info-icon nxFormfieldAppendix [config]="config().infoIcon"></df-info-icon>
  } @if (config().note) {
  <nx-message context="info" nxFormfieldNote>
    <span>{{ config().note | interpolateFromStore | async }}</span>
  </nx-message>
  } @for (message$ of errorMessages(); track $index) {
  <nx-error nxFormfieldError [appearance]="nxErrorAppearance">{{ message$ | async }}</nx-error>
  }
</nx-formfield>

./dropdown.component.scss

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

results matching ""

    No results matching ""