首页 > 解决方案 > 从输入字段获取原始文本而不是日期对象

问题描述

我有一个输入字段,如下面的 html 代码所示。

   <div class="input-group input-group-md">
    <input id="date"    
        name="date"
        [readOnly]="disabled"
        type="text"
        placeholder="M0/d0/0000 Hh:m0:s0"
        [placeholder]="placeholderSet"
        class="form-control"
        data-toggle="tooltip" 
        title="{{tooltipSet}}"
        (focus)="changePlaceholderOnFocus()"
        (focusout)="changePlaceholderOffFocus()"
        [(ngModel)]="searchInput"
        (input)="setSelectedDate()"
        [owlDateTime]="dt"
        >
        <div class="input-group-append">
            <span class="fa fa-calendar input-group-text"
                    [owlDateTimeTrigger]="dt">
            </span>
        </div>
    </div>
<owl-date-time
        [disabled]="disabled"
        [startAt]=""
        [showSecondsTimer]="true"
        #dt>
</owl-date-time>

我想在输入字段中输入原始文本,即当我在输入框中输入日期如12/12/2020 12:13:56时,我得到的日期为Sat Dec 12 2020 12:13:56 GMT+0530(印度标准时间) )在代码中,而不是我在输入框中输入的 mm/dd/yyyy hh:mm:ss 格式。我想从输入框天气中获取数据,它是否是日期。我正在使用OwlDateTime选择器。

下面是ts代码。

export class DateTimePickerComponent implements OnInit, OnDestroy {

  @Input() disabled: any;
  @Input() placeholderSet: any;
  @Input() tooltipSet: any;
  @Input() selectedDropDown: any;
  @Input()
  parentSubject: Subject<any>;
  searchInput: string;
  temp: any;

  constructor() {
  }

  @Output() selectedDate = new EventEmitter<any>();

  setSelectedDate() {
    this.searchInput = String(this.searchInput);
    this.selectedDate.emit(this.searchInput);
  }

可以看到 searchInput 是字符串。您还可以在附加的屏幕截图中检查它正在将其转换为正确的 js 日期格式。

在此处输入图像描述

标签: htmlangulartypescript

解决方案


我使用 ElementRef 来解决这个问题。检查下面更新的 HTML 和 TS 代码。HTML 代码:

    <input
            #dateTimeInput
            id="date"
            name="date"
            type="text"
            class="form-control"
            data-toggle="tooltip"
            title="{{tooltipSet}}"
            [readOnly]="disabled"
            [placeholder]="placeholderSet"
            [(ngModel)]="searchInput"
            (focus)="changePlaceholderOnFocus()"
            (focusout)="changePlaceholderOffFocus()"
            (dateTimeInput)="setSelectedDate()"
            [owlDateTime]="dt"
    >

TS 代码:

export class DateTimePickerComponent implements OnInit, OnDestroy {
  @ViewChild('dateTimeInput') dateTimeInput: ElementRef;
  @Input() disabled: any;
  @Input() placeholderSet: any;
  @Input() tooltipSet: any;
  @Input() selectedDropDown: any;
  @Input()
  parentSubject: Subject<any>;
  searchInput: Date;
  temp: any;

  constructor(private renderer: Renderer2) {
        this.searchInput= null;
    }

  @Output() selectedDate = new EventEmitter<any>();

  setSelectedDate() {
    this.selectedDate.emit(this.dateTimeInput.nativeElement.value);
  }

推荐阅读