且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实现 ControlValueAccessor 的 Angular 2 指令不会在更改时更新“触摸"属性

更新时间:2023-02-13 20:45:13

对于那些最终遇到同样问题的人,我想出了一种方法来管理它,如下所示:

For those who eventually have the same problem, I figured out a way to manage it, as you can below:

import {Directive, ElementRef, Input, forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms";

declare  var $:any;

export const CUSTOM_INPUT_DATE_PICKER_CONTROL_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => DatePickerDirective),
  multi: true
};

@Directive({
  selector: '[date-picker]',
  host: {'(blur)': 'onTouched($event)'},
  providers: [CUSTOM_INPUT_DATE_PICKER_CONTROL_VALUE_ACCESSOR]
})
export class DatePickerDirective implements ControlValueAccessor {
  private innerValue: string;

  @Input('changeMonth') changeMonth:boolean = true;
  @Input('changeYear') changeYear:boolean = true;

  constructor(private el: ElementRef) {
    $(this.el.nativeElement).datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: 'dd/mm/yy'
    }).on('change', e => this.onChange(e.target.value));
  }

  public onChange: any = (_) => { /*Empty*/ }
  public onTouched: any = () => { /*Empty*/ }

  get value(): any {
    return this.innerValue;
  };

  //set accessor including call the onchange callback
  set value(v: any) {
    if (v !== this.innerValue) {
      this.innerValue = v;
      this.onChange(v);
    }
  }

  writeValue(val: string) : void {
    this.innerValue = val;
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

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