79795402

Date: 2025-10-21 01:21:50
Score: 4.5
Natty:
Report link

code not run



import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[formatDate]', // Este é o seletor que você usará no HTML
  standalone: true // Torna a diretiva autônoma (não precisa ser declarada em um módulo)
})
export class FormataDateDirective {

  constructor(private el: ElementRef) {}

  /**
   * O HostListener escuta eventos no elemento hospedeiro (o <input>).
   * Usamos o evento 'input' porque ele captura cada alteração,
   * incluindo digitação, colagem e exclusão de texto.
   * @param event O evento de entrada disparado.
   */
  @HostListener('input', ['$event'])
  onInputChange(event: Event): void {
    const inputElement = event.target as HTMLInputElement;
    let inputValue = inputElement.value.replace(/\D/g, ''); // Remove tudo que não for dígito

    // Limita a entrada a 8 caracteres (DDMMAAAA)
    if (inputValue.length > 8) {
      inputValue = inputValue.slice(0, 8);
    }

    let formattedValue = '';

    // Aplica a formatação DD/MM/AAAA conforme o usuário digita
    if (inputValue.length > 0) {
      formattedValue = inputValue.slice(0, 2);
    }
    if (inputValue.length > 2) {
      formattedValue = `${inputValue.slice(0, 2)}/${inputValue.slice(2, 4)}`;
    }
    if (inputValue.length > 4) {
      formattedValue = `${inputValue.slice(0, 2)}/${inputValue.slice(2, 4)}/${inputValue.slice(4, 8)}`;
    }

    // Atualiza o valor do campo de entrada
    inputElement.value = formattedValue;
  }

  /**
   * Este listener lida com o pressionamento da tecla Backspace.
   * Ele garante que a barra (/) seja removida junto com o número anterior,
   * proporcionando uma experiência de usuário mais fluida.
   */
  @HostListener('keydown.backspace', ['$event'])
  onBackspace(event: KeyboardEvent): void {
    const inputElement = event.target as HTMLInputElement;
    const currentValue = inputElement.value;

    if (currentValue.endsWith('/') && currentValue.length > 0) {
      // Remove a barra e o número anterior de uma vez
      inputElement.value = currentValue.slice(0, currentValue.length - 2);
      // Previne o comportamento padrão do backspace para não apagar duas vezes
      event.preventDefault();
    }
  }
}


<main class="center"> <router-outlet></router-outlet> <input type="text" placeholder="DD/MM/AAAA" [formControl]="dateControl" formatDate maxlength="10"


</main>
Reasons:
  • Blacklisted phrase (3): você
  • Blacklisted phrase (1): porque
  • Blacklisted phrase (1): não
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: teletubbies dipicie