选择日期时间控件, 基于ng-zorro

import { Component, forwardRef, OnInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-date-time',
  template:
  `
  <nz-date-picker [(ngModel)]="date" (ngModelChange)="onDateChange($event)"></nz-date-picker>
  <nz-time-picker [(ngModel)]="time" (ngModelChange)="onTimeChange($event)" nzFormat="HH:mm" [(nzOpen)]="timeOpen"></nz-time-picker>
  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => DateTimeComponent),
      multi: true
    }
  ],
  // NG_VALIDATORS 是让控件注册成为一个可以让表单得到其验证状态的控件
})
// 时间框 可手输。 选秒后自动缩回。
export class DateTimeComponent implements ControlValueAccessor {
    time: Date;
    date: Date;
    disabled: boolean;
    timeOpen: boolean = false;

    onChange: (value: Date) => void = () => null;
    onTouched: () => void = () => null;

    onDateChange(date: Date) {
      console.log(date);
      if (date) {
        if (this.time) {
          this.time.setFullYear(date.getFullYear());
          this.time.setMonth(date.getMonth());
          this.time.setDate(date.getDate());
          this.onChange(this.time);
        } else {
          this.timeOpen = true;
          this.time = new Date(date);
          this.onChange(this.time);
        }
      } else {
        this.onChange(null);
      }
    }
    onTimeChange(time: Date) {
      console.log(time);
      if (time) {
        if (this.date) {
          this.time.setFullYear(this.date.getFullYear());
          this.time.setMonth(this.date.getMonth());
          this.time.setDate(this.date.getDate());
          this.onChange(this.time);
        } else {
          this.date = new Date(this.time);
          this.onChange(this.time);
        }
      } else {
        this.onChange(null);
      }
    }
    // ControlValueAccessor 的四个方法
    /*
    任何 FormControl 显式调用Api的 值 操作(如 patchValue() )都将调用自定义表单组件的 writeValue() 方法,并将新值作为参数传入。数据流向: form model -> component
    */
    writeValue(value: Date) {
      console.log(value);
      this.time = value;
      this.date = new Date(this.time);
    }

    registerOnChange(fn: (value: Date) => void) {
      this.onChange = fn;
    }
    registerOnTouched(fn: () => void) {
      this.onTouched = fn;
    }
    setDisabledState(isDisabled: boolean) {
      this.disabled = isDisabled;
    }
}

猜你喜欢

转载自blog.csdn.net/u013475983/article/details/102782303