File

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

Description

Componente de input com máscara que estende SqInputFormControlComponent. Implementa ControlValueAccessor e Validator para integração com Reactive Forms. Usa a biblioteca ngx-mask para aplicar máscaras de formatação no input.

See https://github.com/JsDaddy/ngx-mask

Example :
```html
<!-- Telefone -->
<sq-input-mask-form-control
  [formControl]="phoneControl"
  [label]="'Telefone'"
  [mask]="'(00) 00000-0000'"
></sq-input-mask-form-control>

<sq-input-mask-form-control [formControl]="cpfControl" [label]="'CPF'" [mask]="'000.000.000-00'"

<sq-input-mask-form-control [formControl]="priceControl" [label]="'Preço'" [mask]="'separator.2'" [thousandSeparator]="'.'" [prefix]="'R$ '"

Example :

Extends

SqInputFormControlComponent

Implements

OnInit

Metadata

Index

Properties
Methods
Inputs
Outputs

Inputs

allowNegativeNumbers
Type : boolean
Default value : false

Indicates whether negative numbers are allowed.

decimalMarker
Type : "." | "," |
Default value : ['.', ',']

The decimal marker character or an array of characters to represent decimal values.

leadZero
Type : boolean
Default value : false

Indicates whether leading zeros should be preserved.

mask
Type : string
Default value : ''

The mask pattern for input validation and formatting.

Example :
```html
```html
maxValue
Type : number

Defines the maximum value that can be accepted as input (for numeric masks).

minValue
Type : number

Defines the minimum value that can be accepted as input (for numeric masks).

placeHolderCharacter
Type : string
Default value : ''

The character to use as a placeholder in empty mask slots.

Example :
prefix
Type : string
Default value : ''

The prefix to be prepended to the input value.

Example :
```html
showMaskTyped
Type : boolean
Default value : false

Indicates whether the mask should be visible while typing.

suffix
Type : string
Default value : ''

The suffix to be appended to the input value.

Example :
```html
thousandSeparator
Type : string
Default value : ''

The character used as a thousand separator in numeric input.

Example :
```html
backgroundColor
Type : string
Default value : ''

Background color of the input element.

borderColor
Type : string
Default value : ''

Border color of the input element.

customClass
Type : string
Default value : ''

Custom CSS class for the input element.

id
Type : string

The id attribute for the input element.

inputMode
Type : string
Default value : ''

Input mode for mobile devices.

label
Type : string

An optional label for the input.

labelColor
Type : string
Default value : ''

Color of the input label.

maxLength
Type : number | null
Default value : null

Maximum length for the input element.

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

The name attribute for the input element.

pattern
Type : string
Default value : ''

Regular expression pattern for input validation.

placeholder
Type : string
Default value : ''

Placeholder text for the input element.

readonly
Type : boolean
Default value : false

Flag to make the input element readonly.

timeToChange
Type : number
Default value : 0

Time in milliseconds before triggering input timeout (debounce).

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.

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

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

Outputs

blurred
Type : EventEmitter<FocusEvent>

Event emitter for blur events.

focused
Type : EventEmitter<FocusEvent>

Event emitter for focus events.

keyPressDown
Type : EventEmitter<KeyboardEvent>

Event emitter for keydown events.

keyPressUp
Type : EventEmitter<KeyboardEvent>

Event emitter for keyup events.

valueChange
Type : EventEmitter<any>

Event emitter for input value changes.

Methods

ngOnInit
ngOnInit()

Lifecycle hook executado após a inicialização do componente. Força o tipo como 'text' para compatibilidade com máscaras.

Returns : void
ngOnChanges
ngOnChanges(changes: SimpleChanges)

Lifecycle hook called when any input property changes. Updates validators when the type changes.

Parameters :
Name Type Optional
changes SimpleChanges No
Returns : void
ngOnDestroy
ngOnDestroy()

Cleanup on component destruction.

Returns : void
onBlur
onBlur(event: FocusEvent)

Handle blur events.

Parameters :
Name Type Optional
event FocusEvent No
Returns : void
onChangeEvent
onChangeEvent(event: Event)

Handle input value changes with optional debounce.

Parameters :
Name Type Optional
event Event No
Returns : void
onFocus
onFocus(event: FocusEvent)

Handle focus events.

Parameters :
Name Type Optional
event FocusEvent No
Returns : void
onKeyDown
onKeyDown(event: KeyboardEvent)

Handle keydown events.

Parameters :
Name Type Optional Description
event KeyboardEvent No
  • The keydown event.
Returns : void
onKeyUp
onKeyUp(event: KeyboardEvent)

Handle keyup events.

Parameters :
Name Type Optional Description
event KeyboardEvent No
  • The keyup event.
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
registerOnValidatorChange
registerOnValidatorChange(fn: () => void)

Validator: Registers a callback for validation changes.

Parameters :
Name Type Optional Description
fn function 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
Private updateValidators
updateValidators()

Updates validators based on the input type. Automatically applies appropriate validators for email, phone, URL, etc. Uses ValidatorHelper through InputValidators for consistency.

Returns : void
validate
validate()

Validator: Validates the control.

Returns : ValidationErrors | null

Validation errors or null.

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

control
Default value : new FormControl('')

Internal FormControl for managing the input value and state.

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

Subject for managing subscriptions.

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.

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

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

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

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

Private onValidationChange
Type : function
Default value : () => {...}

External validator function (propagated from parent control).

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

Reference to a right-aligned label template.

Private Optional timeoutInput
Type : ReturnType<>

Timeout for input changes (debounce).

import { Component, Input, forwardRef, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { NG_VALUE_ACCESSOR, NG_VALIDATORS, ReactiveFormsModule } from '@angular/forms';
import { NgClass, NgStyle, NgTemplateOutlet } from '@angular/common';
import { NgxMaskDirective } from 'ngx-mask';
import { SqInputFormControlComponent } from '../sq-input-form-control/sq-input-form-control.component';
import { SqTooltipComponent } from '../sq-tooltip/sq-tooltip.component';
import { UniversalSafePipe } from '../../pipes/universal-safe/universal-safe.pipe';

/**
 * Componente de input com máscara que estende SqInputFormControlComponent.
 * Implementa ControlValueAccessor e Validator para integração com Reactive Forms.
 * Usa a biblioteca ngx-mask para aplicar máscaras de formatação no input.
 *
 * @see {@link https://github.com/JsDaddy/ngx-mask}
 *
 * @example
 * ```html
 * <!-- Telefone -->
 * <sq-input-mask-form-control
 *   [formControl]="phoneControl"
 *   [label]="'Telefone'"
 *   [mask]="'(00) 00000-0000'"
 * ></sq-input-mask-form-control>
 *
 * <!-- CPF -->
 * <sq-input-mask-form-control
 *   [formControl]="cpfControl"
 *   [label]="'CPF'"
 *   [mask]="'000.000.000-00'"
 * ></sq-input-mask-form-control>
 *
 * <!-- Valor monetário -->
 * <sq-input-mask-form-control
 *   [formControl]="priceControl"
 *   [label]="'Preço'"
 *   [mask]="'separator.2'"
 *   [thousandSeparator]="'.'"
 *   [prefix]="'R$ '"
 * ></sq-input-mask-form-control>
 * ```
 */
@Component({
  selector: 'sq-input-mask-form-control',
  templateUrl: './sq-input-mask-form-control.component.html',
  styleUrls: ['./sq-input-mask-form-control.component.scss'],
  standalone: true,
  imports: [
    NgClass,
    NgStyle,
    NgTemplateOutlet,
    ReactiveFormsModule,
    NgxMaskDirective,
    SqTooltipComponent,
    UniversalSafePipe,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => SqInputMaskFormControlComponent),
      multi: true,
    },
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(() => SqInputMaskFormControlComponent),
      multi: true,
    },
  ],
})
export class SqInputMaskFormControlComponent extends SqInputFormControlComponent implements OnInit {
  /**
   * The mask pattern for input validation and formatting.
   * @example '(00) 00000-0000' para telefone
   * @example '000.000.000-00' para CPF
   * @example 'separator.2' para valores monetários com 2 casas decimais
   */
  @Input() mask = '';

  /**
   * The character used as a thousand separator in numeric input.
   * @default ''
   * @example '.' para formato brasileiro (1.000,00)
   * @example ',' para formato americano (1,000.00)
   */
  @Input() thousandSeparator = '';

  /**
   * The suffix to be appended to the input value.
   * @default ''
   * @example ' kg' para peso
   * @example ' m²' para área
   */
  @Input() suffix = '';

  /**
   * The prefix to be prepended to the input value.
   * @default ''
   * @example 'R$ ' para moeda brasileira
   * @example '$ ' para dólar
   */
  @Input() prefix = '';

  /**
   * Indicates whether the mask should be visible while typing.
   * @default false
   */
  @Input() showMaskTyped = false;

  /**
   * Indicates whether negative numbers are allowed.
   * @default false
   */
  @Input() allowNegativeNumbers = false;

  /**
   * The decimal marker character or an array of characters to represent decimal values.
   * @default ['.', ',']
   */
  @Input() decimalMarker: '.' | ',' | ['.', ','] = ['.', ','];

  /**
   * The character to use as a placeholder in empty mask slots.
   * @default ''
   * @example '_' para mostrar (___) _____-____
   */
  @Input() placeHolderCharacter = '';

  /**
   * Indicates whether leading zeros should be preserved.
   * @default false
   */
  @Input() leadZero = false;

  /**
   * Defines the minimum value that can be accepted as input (for numeric masks).
   * @default undefined
   */
  @Input() minValue?: number;

  /**
   * Defines the maximum value that can be accepted as input (for numeric masks).
   * @default undefined
   */
  @Input() maxValue?: number;

  /**
   * Lifecycle hook executado após a inicialização do componente.
   * Força o tipo como 'text' para compatibilidade com máscaras.
   */
  ngOnInit(): void {
    // Força o tipo para 'text' (máscaras não funcionam bem com outros tipos)
    this.type = 'text';
  }
}

<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 [ngStyle]="{ color: labelColor }" [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,
      }"
      [ngStyle]="{
        'background-color': backgroundColor,
        'border-color': borderColor,
      }"
      [id]="id"
      type="text"
      [name]="name"
      [placeholder]="placeholder || ''"
      [readonly]="readonly"
      [formControl]="control"
      [maxlength]="maxLength"
      (input)="onChangeEvent($event)"
      (keydown)="onKeyDown($event)"
      (keyup)="onKeyUp($event)"
      (blur)="onBlur($event)"
      (focus)="onFocus($event)"
      [pattern]="pattern"
      [attr.inputmode]="inputMode"
      mask="{{ mask }}"
      [thousandSeparator]="thousandSeparator"
      [suffix]="suffix"
      [prefix]="prefix"
      [showMaskTyped]="showMaskTyped"
      [allowNegativeNumbers]="allowNegativeNumbers"
      [decimalMarker]="decimalMarker"
      [placeHolderCharacter]="placeHolderCharacter"
      [leadZero]="leadZero"
    />
    @if (rightLabel) {
      <span class="input-group-text m-0">
        <ng-container *ngTemplateOutlet="rightLabel"></ng-container>
      </span>
    }
  </div>
  @if (maxLength) {
    <div class="d-flex justify-content-end mt-1">
      <small class="text-muted"> {{ maxLength - (control.value?.length || 0) }} caracteres restantes </small>
    </div>
  }
</div>

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

// Importa os estilos do componente pai
@use '../sq-input-form-control/sq-input-form-control.component';
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""