All files / element-ng/form/si-form-field si-form-field.component.ts

96.87% Statements 62/64
92.1% Branches 35/38
91.3% Functions 21/23
100% Lines 47/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165                                                                                                            140x 37x           43x   43x 43x   43x   43x   43x     43x 42x 42x     43x 43x 43x     43x 43x 43x       43x   43x       43x     43x     43x     43x   43x 67x 67x       43x   43x     43x 62x 62x 40x     22x       43x 6x 6x     43x 43x 63x       43x 43x 43x           43x                   63x 63x 20x   43x        
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { NgTemplateOutlet } from '@angular/common';
import {
  Component,
  computed,
  contentChild,
  DestroyRef,
  effect,
  inject,
  input,
  isSignal
} from '@angular/core';
import { FormField } from '@angular/forms/signals';
import { SiTranslatePipe, TranslatableString } from '@siemens/element-translate-ng/translate';
 
import { SiFormFieldsetComponent } from '../form-fieldset/si-form-fieldset.component';
import { SiFormFieldsetControl } from '../form-fieldset/si-form-fieldset.control';
import { SI_FORM_ITEM_CONTROL } from '../si-form-item.control';
import { SiFormValidationErrorService } from '../si-form-validation-error.service';
 
/**
 * Constructs a full form field including error messages, labels and aria-* attributes.
 * It must be used with Angular's signal forms.
 *
 * @example
 * ```html
 * <si-form-field label="Name">
 *   <input class="form-control" [formField]="form.name" />
 *
 *   <!-- Optional help button -->
 *   <button
 *     si-help-button
 *     type="button"
 *     siHelpTitle="Help for name"
 *     siHelpContent="The context help description"
 *   >More information about the name</button>
 * </si-form-field>
 * ```
 */
@Component({
  selector: 'si-form-field',
  imports: [SiTranslatePipe, NgTemplateOutlet],
  templateUrl: './si-form-field.component.html',
  styleUrl: './si-form-field.component.scss',
  host: {
    '[class.required]': 'showRequired()',
    '[class.form-check]': 'isFormCheck()',
    '[class.form-check-inline]': 'fieldset?.inline()',
    '[class.si-form-input]': '!fieldset'
  }
})
export class SiFormFieldComponent implements SiFormFieldsetControl {
  private static idCounter = 0;
 
  /**
   * The label to be displayed in the form field.
   * It will be translated if a translation key is available.
   */
  readonly label = input.required<TranslatableString>();
 
  private readonly formField = contentChild.required(FormField);
  private readonly fieldControl = contentChild(SI_FORM_ITEM_CONTROL, { descendants: true });
 
  protected readonly fieldset = inject(SiFormFieldsetComponent, { optional: true });
 
  private readonly validationErrorService = inject(SiFormValidationErrorService);
 
  private readonly generatedId = `__si-form-field-${SiFormFieldComponent.idCounter++}`;
 
  /** The id of the connected control, used for the label's `for` attribute. */
  protected readonly controlId = computed(() => {
    const id = this.fieldControl()?.id;
    return (isSignal(id) ? id() : id) ?? (this.formField().element.id || this.generatedId);
  });
 
  protected readonly errormessageId = computed(() => {
    const id = this.fieldControl()?.errormessageId;
    return (isSignal(id) ? id() : id) ?? `${this.controlId()}-errormessage`;
  });
 
  protected readonly labelledby = computed(() => {
    const labelledby = this.fieldControl()?.labelledby;
    return isSignal(labelledby) ? labelledby() : labelledby;
  });
 
  /** Whether the connected control is a form-check (checkbox, radio or switch). */
  protected readonly isFormCheck = computed(
    () =>
      this.fieldControl()?.isFormCheck ??
      this.formField().element.classList.contains('form-check-input')
  );
 
  private readonly fieldState = computed(() => this.formField().state());
 
  /** @internal */
  readonly control = computed(() => this.fieldState().fieldTree);
 
  /** @internal */
  readonly required = computed(() => this.fieldState().required());
 
  /** @internal  */
  readonly showRequired = computed(() => this.required() && !this.isPartOfRadioGroup());
 
  private readonly invalid = computed(() => {
    const state = this.fieldState();
    return state.touched() && state.invalid();
  });
 
  /** @internal */
  readonly touched = computed(() => this.fieldState().touched());
 
  protected readonly isPartOfRadioGroup = computed(() => this.fieldset?.hasOnlyRadios() ?? false);
 
  /** @internal */
  readonly errors = computed(() => {
    const state = this.fieldState();
    if (!state.touched()) {
      return [];
    }
 
    return this.validationErrorService.resolveFormFieldErrors(state);
  });
 
  constructor() {
    if (this.fieldset) {
      this.fieldset.registerControl(this);
      inject(DestroyRef).onDestroy(() => this.fieldset!.unregisterControl(this));
    }
 
    effect(() => this.syncControlId());
    effect(() => this.syncErrorDescription());
    effect(() => this.syncInvalidState());
  }
 
  private syncControlId(): void {
    const element = this.formField().element;
    Eif (!element.id) {
      element.id = this.generatedId;
    }
  }
 
  /** Associates the error messages with the projected control for assistive technologies. */
  private syncErrorDescription(): void {
    this.formField().element.setAttribute('aria-describedby', this.errormessageId());
  }
 
  /**
   * Reflects the validation state onto the projected control via `aria-invalid`. This is needed
   * because signal forms does not set `aria-invalid`, and the native `:user-invalid` pseudo-class
   * ignores `markAsTouched()`. The matching `.ng-invalid`/`.ng-touched` classes that drive the
   * styling are added by signal forms itself, see `provideSiFormFieldConfig()`.
   */
  private syncInvalidState(): void {
    const element = this.formField().element;
    if (this.invalid()) {
      element.setAttribute('aria-invalid', 'true');
    } else {
      element.removeAttribute('aria-invalid');
    }
  }
}