File

src/components/sq-input-form-control/sq-input-form-control.component.ts

Description

Componente de input moderno que implementa ControlValueAccessor. Versão melhorada do sq-input com suporte completo a Reactive Forms.

Usa um FormControl interno para gerenciar o valor e estado. Não aplica validações internas - todas as validações devem ser definidas no FormControl externo. Suporta debounce, customização de estilos, tooltips, e templates customizados. Aplica automaticamente estilos de erro baseados no estado do FormControl externo.

Example :
```html
<sq-input-form-control
  formControlName="email"
  [label]="'Email'"
  [type]="'email'"
  [placeholder]="'seu@email.com'"
  [tooltipMessage]="'Digite um email válido'"
></sq-input-form-control>
Example :

Extends

SqFormControlBaseDirective

Metadata

Index

Properties
Methods
Inputs
Outputs

Inputs

inputMode
Type : string
Default value : ''

Input mode for mobile devices.

timeToChange
Type : number
Default value : 0

Time in milliseconds for debouncing value changes. When set to a value > 0, the value change will be debounced.

type
Type : "text" | "email" | "email-multiple" | "hidden" | "password" | "tel" | "url" | "file"
Default value : 'text'

Type of the input element (e.g., text, email, password).

customClass
Type : string
Default value : ''

Custom CSS class for the input element.

id
Type : string

The id attribute for the input element.

label
Type : string

An optional label for the input.

name
Type : string
Default value : `random-name-${(1 + Date.now() + Math.random()).toString().replace('.', '')}`

The name attribute for the input element.

placeholder
Type : string
Default value : ''

Placeholder text for the input element.

readonly
Type : boolean
Default value : false

Flag to make the input element readonly.

tooltipColor
Type : string
Default value : 'inherit'

Color of the tooltip.

tooltipIcon
Type : string
Default value : ''

Icon for the tooltip.

tooltipMessage
Type : string
Default value : ''

Tooltip message to display.

tooltipPlacement
Type : "center top" | "center bottom" | "left center" | "right center"
Default value : 'right center'

Placement of the tooltip.

Outputs

blurred
Type : EventEmitter<FocusEvent>

Event emitter for blur events.

focused
Type : EventEmitter<FocusEvent>

Event emitter for focus events.

valueChange
Type : EventEmitter<any>

Event emitter for input value changes.

Methods

watchValueChanges
watchValueChanges()

Override the watchValueChanges method to add debounce time.

Returns : void
ngOnDestroy
ngOnDestroy()

Cleanup on component destruction.

Returns : void
ngOnInit
ngOnInit()

Lifecycle hook that sets up value change subscriptions with optional debounce.

Returns : void
onBlur
onBlur(event: FocusEvent)

Handle blur events. Marks the control as touched when the user leaves the input.

Parameters :
Name Type Optional Description
event FocusEvent No
  • The focus event that triggered the blur.
Returns : void
onFocus
onFocus(event: FocusEvent)

Handle focus events. Emits the focused event when the input receives focus.

Parameters :
Name Type Optional Description
event FocusEvent No
  • The focus event that triggered the focus.
Returns : void
registerOnChange
registerOnChange(fn: any)

ControlValueAccessor: Registers a callback function that is called when the control's value changes.

Parameters :
Name Type Optional Description
fn any No
  • The callback function.
Returns : void
registerOnTouched
registerOnTouched(fn: any)

ControlValueAccessor: Registers a callback function that is called when the control is touched.

Parameters :
Name Type Optional Description
fn any No
  • The callback function.
Returns : void
setDisabledState
setDisabledState(isDisabled: boolean)

ControlValueAccessor: Sets the disabled state of the control.

Parameters :
Name Type Optional Description
isDisabled boolean No
  • Whether the control should be disabled.
Returns : void
writeValue
writeValue(value: any)

ControlValueAccessor: Writes a new value to the element.

Parameters :
Name Type Optional Description
value any No
  • The new value.
Returns : void

Properties

labelTemplate
Type : TemplateRef<HTMLElement> | null
Default value : null
Decorators :
@ContentChild('labelTemplate')

Reference to a label template.

leftLabel
Type : TemplateRef<HTMLElement> | null
Default value : null
Decorators :
@ContentChild('leftLabel')

Reference to a left-aligned label template.

nativeElement
Type : ElementRef
Default value : inject(ElementRef)

Reference to the native element.

rightLabel
Type : TemplateRef<HTMLElement> | null
Default value : null
Decorators :
@ContentChild('rightLabel')

Reference to a right-aligned label template.

control
Default value : new FormControl<any>(null)

Internal FormControl for managing the input value and state.

Protected destroy$
Default value : new Subject<void>()

Subject for managing subscriptions.

Protected onChange
Type : function
Default value : () => {...}

ControlValueAccessor callback function called when the value changes. Registered via registerOnChange().

Protected onTouched
Type : function
Default value : () => {...}

ControlValueAccessor callback function called when the control is touched. Registered via registerOnTouched().

import {
  Component,
  ContentChild,
  ElementRef,
  Input,
  TemplateRef,
  forwardRef,
  inject,
  ChangeDetectionStrategy,
} from '@angular/core';
import { NgClass, NgTemplateOutlet } from '@angular/common';
import { ReactiveFormsModule, NG_VALUE_ACCESSOR } from '@angular/forms';
import { SqTooltipComponent } from '../sq-tooltip/sq-tooltip.component';
import { UniversalSafePipe } from '../../pipes/universal-safe/universal-safe.pipe';
import { debounceTime, distinctUntilChanged, takeUntil } from 'rxjs/operators';
import { SqFormControlBaseDirective } from '../../directives/sq-form-control-base';

/**
 * Componente de input moderno que implementa ControlValueAccessor.
 * Versão melhorada do sq-input com suporte completo a Reactive Forms.
 *
 * Usa um FormControl interno para gerenciar o valor e estado.
 * Não aplica validações internas - todas as validações devem ser definidas no FormControl externo.
 * Suporta debounce, customização de estilos, tooltips, e templates customizados.
 * Aplica automaticamente estilos de erro baseados no estado do FormControl externo.
 *
 * @example
 * ```html
 * <sq-input-form-control
 *   formControlName="email"
 *   [label]="'Email'"
 *   [type]="'email'"
 *   [placeholder]="'seu@email.com'"
 *   [tooltipMessage]="'Digite um email válido'"
 * ></sq-input-form-control>
 * ```
 */
@Component({
  selector: 'sq-input-form-control',
  templateUrl: './sq-input-form-control.component.html',
  styleUrls: ['./sq-input-form-control.component.scss'],
  standalone: true,
  imports: [NgClass, NgTemplateOutlet, ReactiveFormsModule, SqTooltipComponent, UniversalSafePipe],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => SqInputFormControlComponent),
      multi: true,
    },
  ],
})
export class SqInputFormControlComponent extends SqFormControlBaseDirective {
  /**
   * Time in milliseconds for debouncing value changes.
   * When set to a value > 0, the value change will be debounced.
   * @default 0 (no debounce)
   */
  @Input() timeToChange = 0;

  /**
   * Type of the input element (e.g., text, email, password).
   */
  @Input() type: 'text' | 'email' | 'email-multiple' | 'hidden' | 'password' | 'tel' | 'url' | 'file' = 'text';

  /**
   * Input mode for mobile devices.
   */
  @Input() inputMode = '';

  /**
   * Reference to a left-aligned label template.
   */
  @ContentChild('leftLabel')
  leftLabel: TemplateRef<HTMLElement> | null = null;

  /**
   * Reference to a right-aligned label template.
   */
  @ContentChild('rightLabel')
  rightLabel: TemplateRef<HTMLElement> | null = null;

  /**
   * Reference to a label template.
   */
  @ContentChild('labelTemplate')
  labelTemplate: TemplateRef<HTMLElement> | null = null;

  /**
   * Reference to the native element.
   */
  nativeElement: ElementRef = inject(ElementRef);

  /**
   * Override the watchValueChanges method to add debounce time.
   */
  override watchValueChanges(): void {
    this.control.valueChanges
      .pipe(debounceTime(this.timeToChange ?? 0), distinctUntilChanged(), takeUntil(this.destroy$))
      .subscribe(value => {
        this.onChange(value);
        this.valueChange.emit(value);
      });
  }
}
<div class="wrapper-all-inside-input {{ customClass }}">
  @if (label?.length || tooltipMessage || labelTemplate) {
    <label
      class="display-flex"
      [ngClass]="{
        readonly: readonly,
      }"
      [for]="id"
    >
      @if (label && !labelTemplate) {
        <div [innerHtml]="label | universalSafe"></div>
      }
      @if (labelTemplate) {
        <div>
          <ng-container *ngTemplateOutlet="labelTemplate"></ng-container>
        </div>
      }
      @if (tooltipMessage) {
        <sq-tooltip
          class="ml-1"
          [message]="tooltipMessage"
          [placement]="tooltipPlacement"
          [color]="tooltipColor"
          [icon]="tooltipIcon"
        ></sq-tooltip>
      }
    </label>
  }
  <div
    class="p-0 wrapper-input wrapper-input-squid text-ellipsisarea"
    [ngClass]="{
      readonly: readonly,
    }"
  >
    @if (leftLabel) {
      <span class="input-group-text m-0">
        <ng-container *ngTemplateOutlet="leftLabel"></ng-container>
      </span>
    }
    <input
      class="col input"
      [ngClass]="{
        disabled: disabled,
        readonly: readonly,
      }"
      [id]="id"
      [type]="type || 'text'"
      [name]="name"
      [placeholder]="placeholder || ''"
      [readonly]="readonly"
      [formControl]="control"
      (blur)="onBlur($event)"
      (focus)="onFocus($event)"
      [attr.inputmode]="inputMode"
    />
    @if (rightLabel) {
      <span class="input-group-text m-0">
        <ng-container *ngTemplateOutlet="rightLabel"></ng-container>
      </span>
    }
  </div>
</div>

./sq-input-form-control.component.scss

.wrapper-all-inside-input {
  position: relative;
  .icon {
    margin: 0;
    font-size: 1rem;
    font-weight: 700;
    position: absolute;
    right: 24px;
    top: 40px;
    &.no-label {
      top: 12px;
    }
  }
  .icon-external {
    color: inherit !important;
  }
  .max-length-name {
    font-size: inherit;
    float: right;
  }
}

Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""