Home > database >  Angular: How to add a fixed colon for a time field and automatically step over it?
Angular: How to add a fixed colon for a time field and automatically step over it?

Time:10-16

I have the following input field in my angular 14 application:

    <mdb-form-control>
      <input id="arrivalTime" mdbInput
             type="text"  placeholder="--:--"/>
      <label mdbLabel >Arrival Time</label>
    </mdb-form-control>

I am wondering how I can add a permanent ":" so that when the user types in a time it automatically steps to the other side of the colon

Basically like in this: https://www.npmjs.com/package/jquery-clock-timepicker

Thanks

CodePudding user response:

basically you need to listen to the change event of the input field. In the function you define your criteria when to put a colon. Also in the event handler you can have use of the <control>.setSelectionRange method to set the cursor position accordingly. You could even use a custom pipe function to set the colon accordingly. Check the documentation for setSelectionRange.

CodePudding user response:

You can create a custom directive to format the time

@Directive({
  selector: '[appFormatTime]',
})
export class FormatTimeDirective {
  constructor(private element: ElementRef) {}

  @HostListener('input') logChange() {
    let val = this.element.nativeElement.value.replace(/:/g, '');
    val = val.match(/.{1,2}/g).join(":")
    this.element.nativeElement.value = val.substring(0, 5);
  }
}
<mdb-form-control>
  <input
    id="arrivalTime"
    mdbInput
    type="text"
    
    placeholder="--:--"
    appFormatTime
  />
  <label mdbLabel >Arrival Time</label>
</mdb-form-control>
  • Related