깜놀하는 해므찌로

Angular 사업자 번호 input 컴포넌트 예시 / 사업자 번호 정규식 본문

IT

Angular 사업자 번호 input 컴포넌트 예시 / 사업자 번호 정규식

agnusdei1207 2023. 4. 28. 11:55
반응형
SMALL
<input
  #input
  [disabled]="disabled"
  [(ngModel)]="value"
  [maxlength]="maxlength ?? null"
  [placeholder]="placeholder ?? ''"
  [autofocus]="_autofocus"
  oninput="this.value = this.value.replace(/[^0-9.]/g, '')
  .replace(/(\..*)\./g, '$1')
  .replace(/^(\d{0,3})(\d{0,4})(\d{0,4})$/, `$1-$2-$3`)
  .replace(/\-{1,2}$/g, '');"
  class="w-full px-3 py-2.5 text-sm border outline-none border-gray-200 hover:border-gray-500 focus-within:border-gray-500 rounded-md"
/>
import { ReactiveFormsModule, NgControl, FormsModule } from '@angular/forms';
import {
  Component,
  Input,
  ElementRef,
  Optional,
  Self,
  ViewChild,
} from '@angular/core';
import { CustomValueAccessor } from '../custom-value-accessor';

@Component({
  selector: 'app-input-tel',
  templateUrl: './input-tel.component.html',
  styleUrls: ['./input-tel.component.scss'],
  standalone: true,
  imports: [ReactiveFormsModule, FormsModule],
})
export class InputTelComponent extends CustomValueAccessor<string> {
  _autofocus: boolean = false;

  @ViewChild('input') input: ElementRef<HTMLInputElement> | undefined;
  @Input() class?: string | undefined;
  @Input() id?: string | undefined;
  @Input() formControlName?: string | undefined;
  @Input() fixText?: string | undefined;
  @Input() maxlength?: string | number | null;
  @Input() placeholder?: string | undefined;
  @Input() override required: boolean = false;
  @Input()
  set autofocus(value: string | boolean) {
    this._autofocus = typeof value === 'string' ? value !== undefined : value;
  }

  constructor(@Self() @Optional() public ngControl: NgControl) {
    super();
    if (this.ngControl) {
      this.ngControl.valueAccessor = this;
    }
  }

  get invalid(): boolean {
    return (this.ngControl?.dirty ?? false) && !this.ngControl?.valid;
  }
}

1. 단일 컴포넌트

 

 

 

import { AbstractControl, ControlValueAccessor, ValidationErrors, Validator } from "@angular/forms";

export class CustomValueAccessor<T> implements ControlValueAccessor, Validator {
    disabled = false;
    required: boolean = false;
    touched: boolean = false;
    onChange: any = (value: T) => { };
    onTouched: any = () => { };
    onValidationchange: any = () => { };

    private _value!: T;

    set value(newValue: T) {
        if (this._value === newValue) { return; }
        this._value = newValue;
        this.onChange(newValue);
        this.onTouched();
        this.touched = true // 이벤트 트리거 시 컨트롤 표시
    }

    get value(): T {
        return this._value;
    }

    writeValue(value: T): void {
        this.value = value;
    }

    registerOnChange(fn: (value: T) => {}): void {
        this.onChange = fn;
    }

    registerOnTouched(fn: () => {}): void {
        this.onTouched = fn;
    }

    setDisabledState?(isDisabled: boolean): void {
        this.disabled = isDisabled;
    }

    validate(control: AbstractControl<any, any>): ValidationErrors | null {
        return this.required && this.touched ? !this._value ? { required: true } : null : null
    }

    registerOnValidatorChange?(fn: () => void): void {
        this.onValidationchange = fn
    }

}

2. 앵귤러 제공 controllValueAccessor

 

 

 

 

 

<div class="flex flex-col gap-2">
    <div>사업자 정보*</div>
    <app-input-business-number
      placeholder="사업자 등록번호를 입력해주세요"
      formControlName="businessNumber"
      maxlength="12"
    />
  </div>

3. 컴포넌트 장착 및 호출하여 사용하는 부분

반응형
LIST